# 270 Closest Binary Search Tree Value

給一棵BST和int target,

要在BST中找到和target最接近的數字值。

Concept:

int dif to record minimum difference int min to record the value with minimum difference

traverse BST,當root < target時,往left child,不然就往right child。

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int closestValue(TreeNode root, double target) {

        if(root.left==null && root.right==null)
            return root.val;
        double dif = Math.abs(root.val - target);
        int min = -1;
        while(root!=null){
            if(Math.abs(root.val - target)<=dif){
                dif = Math.abs(root.val - target);
                min = root.val;
            }
            if(target<root.val)
                root = root.left;
            else
                root = root.right;

        }
        return min;
    }
}

results matching ""

    No results matching ""