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);
}
}
}