Leetcode 671. Second Minimum Node In a Binary Tree(二叉树中第二小的节点)

Second Minimum Node In a Binary Tree

Given a non-empty special binary tree consisting of nodes with the
non-negative value, where each node in this tree has exactly two or zero
sub-node. If the node has two sub-nodes, then this node's value is the 
smaller value among its two sub-nodes. More formally, 
the property root.val = min(root.left.val, root.right.val) always holds.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

If no such second minimum value exists, output -1 instead.

Example 1:
Input: 
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: 
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
 /**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int first=0;
    int second=-1;
    int findSecondMinimumValue(TreeNode* root) {
        if(root==NULL){
            return-1;
        }
        if(root->left==NULL&&root->right==NULL){
            return -1;
        }
        first=root->val; //根结点一定是最小的
        corefunction(root->left);//对second分别在左右子树中两次更新得到最终的second值(这也是返回值为void的原因,要调用两次)
        corefunction(root->right);
        return second;

    }
private://这个函数是为了找second的值
    void corefunction(TreeNode*root){//更新一颗树的second值
        if(root==NULL){//这部分是对根节点,root为空,root不为空的话就开始比较root值和second
            return;
        }
        //second == -1代表之前还未发现比根节点大的节点
        //如果second != -1且root.val < second 代表已经有比根节点大的值,但是目前的节点是更优解
        if(root->val>first){
            if(second==-1||second>root->val){
                second=root->val;
            }
        }
        corefunction(root->left);
        corefunction(root->right);
    }//例如左子树调用时,此时是对左子树的根节点,左子树的左右子树调用的函数
};
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值