LeetCode671. 二叉树中第二小的节点

题目

纯暴力

 1 class Solution {
 2 public:
 3     vector<int>ans;
 4     int findSecondMinimumValue(TreeNode* root) {
 5         dfs(root);
 6         sort(ans.begin(),ans.end());
 7         int res = ans[0];
 8         for(int i = 1;i < ans.size();i++){
 9             if(ans[i] != res) return ans[i];
10         }
11         return -1;
12     }
13     void dfs(TreeNode* root){
14         if(root!=NULL){
15             dfs(root->left);
16             ans.push_back(root->val);
17             dfs(root->right);
18         }
19     }
20 
21 };

递归

 1 class Solution {
 2 public:
 3     
 4     int findSecondMinimumValue(TreeNode* root) {
 5         if(!root || !root->left || !root->right)  return -1; //不满足题意
 6         int left = root->left->val,right = root->right->val;
 7         if(root->val == root->left->val)  left = findSecondMinimumValue(root->left);
 8         if(root->val == root->right->val)  right = findSecondMinimumValue(root->right);
 9 
10         if(root->val == left && root->val == right ) return -1;
11         if(root->val < min(left,right)) return min(left,right);
12         else return max(left,right);
13     }
14    
15 };

 

posted @ 2021-01-12 16:49  Uitachi  阅读(67)  评论(0)    收藏  举报