270. Closest Binary Search Tree Value

Easy
這道題mock的時候沒做出來,老師說這種送分題應(yīng)該是幾分鐘就寫好的,我汗。

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大,就繼續(xù)看right subtree. 反之則看左子樹。這樣最后traverse完整棵樹的高度而并非每棵樹的節(jié)點,所有用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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容