270. 最接近的二叉搜索樹值

問題
在這裏插入圖片描述

例子

在這裏插入圖片描述

思路

  • 方法1

    二叉搜索樹,考慮類似二分,減少操作

  • 方法2

代碼

//方法1
class Solution {
    private double dist=Double.MAX_VALUE;
    private int res=0;
    public int closestValue(TreeNode root, double target) {
        preOrder(root,target);
        return res;
    }
    public void preOrder(TreeNode root, double target) {
        if(root==null) return;
        
        if(Math.abs(root.val-target)<dist) {
            dist= Math.abs(root.val-target);
            res=root.val;
        }
        //加一個判斷,減少操作
        if(root.val>target)
            if(root.left!=null) preOrder(root.left,target);
        if(root.val<target)
            if(root.right!=null) preOrder(root.right,target);
    }
}
//方法2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章