zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    table表格
    常见页面布局方式(三种框架集)
    学习标签属性3
    学习标签属性2
    学习标签属性1
    Purity in My Programming: Functions in Go
    cron一有趣处
    go函数作为一等民
    LRU算法
    go中的一个网络重连复用
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14267802.html
Copyright © 2011-2022 走看看