671. Second Minimum Node In a Binary Tree [Easy]

这题为什么是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);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值