这题为什么是easy,我做了好久,比中序遍历之类的难多了
/**
* 自己的代码,递归方法
* 根据题意,最初的根节点val一定是最小的,设为first,本题要找的是值比它大的值最小节点
* 对于任何一个节点,其子树节点的val肯定大于or等于它的val
* 所以递归查找子树时,若子树根节点值大于first,则该子树中大于first的最小节点为根节点
* 若子树根节点等于first(不会小于first),则再递归查找其左右子树
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 36.3 MB, less than 54.12%
*/
class Solution {
public int findSecondMinimumValue(TreeNode root) {
TreeNode res = helper(root, root.val);
return res == null ? -1 : res.val;
}
private TreeNode helper(TreeNode root, int first) {
if (root == null)
return null;
if (root.val > first)
return root;
TreeNode left = helper(root.left, first);
if (left == null)
return helper(root.right, first);
TreeNode right = helper(root.right, first);
if (right == null)
return left;
return left.val < right.val ? left : right;
}
}
/**
* 这个解法中很有借鉴意义的有两个操作:
* 1. 将递归中不变的数据用数组保存(如果类型相同),不需要使用全局变量
* 2. 将需要判断是否被赋值过的基本数据类型变量,设为引用数据类型,这样当变量为null就是没有被赋值过
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 35.9 MB, less than 97.70%
*/
class Solution {
public int findSecondMinimumValue(TreeNode root) {
Integer[] res = {root.val, null};
helper(root, res);
return res[1] == null ? -1 : res[1];
}
private void helper(TreeNode root, Integer[] res) {
if (root == null)
return;
if (root.val != res[0] && res[1] == null || root.val > res[0] && root.val < res[1])
res[1] = root.val;
else {
helper(root.left, res);
helper(root.right, res);
}
}
}
/**
* 不需要helper函数的递归方法
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 36.4 MB, less than 36.20%
*/
class Solution {
public int findSecondMinimumValue(TreeNode root) {
if (root == null || root.left == null) // 由题意,左右子节点要么都有要么都没有
return -1;
int left = root.left.val, right = root.right.val;
if (left == root.val)
left = findSecondMinimumValue(root.left);
if (right == root.val)
right = findSecondMinimumValue(root.right);
if (left == -1)
return right;
return right == -1 ? left : Math.min(left, right);
}
}