270. Closest Binary Search Tree Value

Easy
这道题mock的时候没做出来,老师说这种送分题应该是几分钟就写好的,我汗。

recursive way

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int a = root.val;
        TreeNode child = a > target ? root.left : root.right;
        if (child == null){
            return root.val;            
        }
        int b = closestValue(child, target);
        if (Math.abs(a - target) < Math.abs(b - target)){
            return root.val;
        } else {
            return b;
        }
    }
}

recursion写出来跑得挺慢的,才打败4%, 试了一下iterative way,提高到20%左右。下面这个写法最简洁,不过后面的写法更加human一点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int res = root.val;
        while (root != null){
            if (Math.abs(root.val - target) < Math.abs(res - target)){
                res = root.val;
            }
            root = target > root.val ? root.right : root.left;  
        }
        return res;
    }
}

Iterative比较human跟intuitive的写法:思路很代码一样都很straightforward,先keep一个变量minDiff表示最小跟target的差距,然后以root跟target的差initialize. 再看root跟target哪个大,如果target大,就继续看right subtree. 反之则看左子树。这样最后traverse完整棵树的高度而并非每棵树的节点,所有用logN.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int minDiffVal = root.val;
        double minDiff = Math.abs(root.val - target);
        TreeNode curt = root;
        while (curt != null){
            if (Math.abs(curt.val - target) < minDiff){
                minDiff = Math.abs(curt.val - target);
                minDiffVal = curt.val;
            }
            curt = target > curt.val ? curt.right : curt.left;
        }
        return minDiffVal;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/e208ce4e11db
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞