题目描述
给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。
给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
方法思路
Approach #1: Brute Force [Accepted]
raverse the tree with a depth-first search, and record every unique value in the tree using a Set structure uniques.
Then, we’ll look through the recorded values for the second minimum. The first minimum must be root.val\text{root.val}root.val.
class Solution{
//Runtime: 2 ms, faster than 51.91%
//Memory Usage: 36.9 MB, less than 19.37%
private Set<Integer> set;
public int findSecondMinimumValue(TreeNode root){
set = new HashSet<>();
dfs(root);
int min1 = root.val;
long ans = Long.MAX_VALUE;
for (int v : set) {
if (min1 < v && v < ans) ans = v;
}
return ans < Long.MAX_VALUE ? (int) ans : -1;
}
public void dfs(TreeNode root){
if(root != null){
set.add(root.val);
dfs(root.left);
dfs(root.right);
}
}
}
Approach2:
Let min1 = root.val\text{min1 = root.val}min1 = root.val. When traversing the tree at some node, node\text{node}node, if node.val > min1\text{node.val > min1}node.val > min1, we know all values in the subtree at node\text{node}node are at least node.val\text{node.val}node.val, so there cannot be a better candidate for the second minimum in this subtree. Thus, we do not need to search this subtree.
Also, as we only care about the second minimum ans\text{ans}ans, we do not need to record any values that are larger than our current candidate for the second minimum, so unlike Approach #1 we can skip maintaining a Set of values(uniques) entirely.
class Solution {
//Runtime: 1 ms, faster than 100.00%
//Memory Usage: 36.6 MB, less than 85.86%
int min1;
long ans = Long.MAX_VALUE;
public void dfs(TreeNode root) {
if (root != null) {
if (min1 < root.val && root.val < ans) {
ans = root.val;
} else if (min1 == root.val) {
dfs(root.left);
dfs(root.right);
}
}
}
public int findSecondMinimumValue(TreeNode root) {
min1 = root.val;
dfs(root);
return ans < Long.MAX_VALUE ? (int) ans : -1;
}
}