【树】671. 二叉树中第二小的节点

题目:

【树】671. 二叉树中第二小的节点

 

 

解答:

首先递归遍历树,记录下根节点的数据,然后对数据进行排序,从数据头开始遍历,找出第二小的数据。
时间复杂度:o(n)+o(logn/2)
空间复杂度:o(n)

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> answer;
13     void f(TreeNode* root)
14     {
15         if(!root) 
16         {
17             return;
18         }
19 
20         if(!root->right) 
21         {
22           answer.push_back(root->val);
23           return;
24         }
25         f(root->left);
26         f(root->right);
27     }
28     int findSecondMinimumValue(TreeNode* root) 
29     {
30         f(root);
31         sort(answer.begin(),answer.end());
32         if(root == NULL || answer.size()<2 || answer[answer.size()-1] == answer[0]) 
33         {
34             return -1;
35         }
36 
37         int count=answer[0];
38         for(int x:answer)
39         {
40              if(x!=count) 
41              {
42                  return x;
43              }
44         }
45         return -1;
46     }
47 };

 

上一篇:PhD Positions opening at University of Nevada, Reno (Wireless Networking / Cognitive Radio / Wireles


下一篇:Your password does not satisfy the current policy requirements问题解决方法