LeetCode 671. 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.


题目翻译:
给一个非空的包含非负整数的特殊二叉树,该树中每个节点要么不含有子节点,要么包含两个子节点。如果某个节点有两个子节点,那么这个节点的值等于子节点中最小的那个值。更正式的表述为:root.val = min(root.left.val, rootl.right.val),即节点值等于两子节点中最小的节点值。

给一个上述的二叉树,你需要输出整个二叉树中第二小的整数。如果没有第二小的整数,则输出-1.

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.



解题分析:
本题需要对树进行遍历,有两种方案:广度优先遍历和深度优先遍历,本题适合才有深度优先遍历的方案。
由 root.val = min(root.left.val, rootl.right.val)可知,某棵子树的根节点是该子树的最小节点。那么当 父节点root的值不等于某个子节点sub的值时,不用再去搜索以sub节点为根的子树。这是因为sub的值就是以sub为根的子树的最小值,并且此值大于root的值,由于只需要找第二小的值,sub的值即是备选答案之一,因此不用再去搜索以sub节点为根的子树。

int tmpRecursive(struct TreeNode* root){
    if(root->left == NULL){
        return root->val;
    }
    //找左子树的第二小的值
    int left = root->left->val;
    if(root->left->val == root->val){
        left = tmpRecursive(root->left);
    }
    //找右子树的第二小的值
    int right = root->right->val;
    if(root->right->val == root->val){
        right = tmpRecursive(root->right);
    }
    //找第二小的值
    if(left == root->val){
        return right;
    }
    if(right == root->val){
        return left;
    }
    return left > right ? right : left;
}

int findSecondMinimumValue(struct TreeNode* root){
    //单独拎一个函数出来,这是因为 当找不到第二小的值时需要返回-1
    int val = tmpRecursive(root);
    return val == root->val ? -1 : val;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yuzhiyuxia

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值