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.

Example 1:
在这里插入图片描述
Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Constraints:

The number of nodes in the tree is in the range [1, 25].
1 <= Node.val <= 231 - 1
root.val == min(root.left.val, root.right.val) for each internal node of the tree.

给出一个特殊的二叉树,每个节点只有0 or 2个节点,且root的值是左右子树值中较小的那个。
找出第二大的值,如果没有就返回-1

思路:
因为root的值是左右子树中较小的,所以整个二叉树的最小值就是root的值。
刚开始想在左右子树中找到比root大的第一个值就立刻返回,但是发现,假如root是1,左子树是1,右子树是3,如果立刻返回就是3。但是左子树1的下面可能还有2呢。所以要把3保存下来,但是还要遍历1下面的节点,不断地更新第二大的值,可以用DFS实现。
比当前结果还要大的节点就不需要再遍历下去了。

因为值的范围可以到达int型的最大值,所以先用long型最大值,而后更新BS中第二大的值。最后要cast到int。

class Solution {
    long result = Long.MAX_VALUE;
    public int findSecondMinimumValue(TreeNode root) {
        if(root == null) return -1;
        int minV = root.val;
        helper(root, minV);
        return (int)(result == Long.MAX_VALUE ? -1 : result);
    }
    
    void helper(TreeNode root, int minV) {
        if(root == null) return;
        if(root.val > minV && root.val < result) {
            result = root.val;
        } else if(root.val == minV) {
            helper(root.left, minV);
            helper(root.right, minV);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值