题目描述
中文
给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么这个节点
的值不大于它的子节点的值。
给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
英文
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.
示例 1:
输入:
2
/ \
2 5
/ \
5 7
输出: 5
说明: 最小的值是 2 ,第二小的值是 5 。
示例 2:
输入:
2
/ \
2 2
输出: -1
说明: 最小的值是 2, 但是不存在第二小的值。
解题思路
- 简单二叉树的搜索遍历,从题目可以知道根节点是最小的值,而子节点一定大于等于根节点,所以我们只要找到不等于根节点的子节点即可。
- 又因为它有左右两颗子树,所以我们左边选出一个最小值,右边选出一个最小值,最后返回两者更小的即可。
class Solution {
public int findSecondMinimumValue(TreeNode root) {
int min_left = 0, min_right = 0, min = root.val;
min_left = find_diff(min, root.left); //左子树的最小值
min_right = find_diff(min, root.right); //右子树的最小值
if(min_left != -1 && min_right != -1){
return min_left > min_right ? min_right:min_left;
}
else if(min_left != -1){
return min_left;
}
else if(min_right != -1){
return min_right;
}else {
return -1;
}
}
public int find_diff(int min, TreeNode root){ //递归搜索不等于根节点的子节点
if(root == null)
return -1;
if(root.val != min)
return root.val;
else{
int min_left = find_diff(min, root.left);
int min_right = find_diff(min, root.right);
if(min_left != -1 && min_right != -1){
return min_left > min_right ? min_right:min_left;
}
else if(min_left != -1){
return min_left;
}
else if(min_right != -1){
return min_right;
}else {
return -1;
}
}
}
}