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