Closest Binary Search Tree Value

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target.

解题思路:记录一个最近的值,然后沿着二叉搜索的路径一路比较下去,并更新这个最近值就行了。因为我们知道离目标数最接近的数肯定在二叉搜索的路径上。

public int closestValue(TreeNode root, double target) {
    int closest = root.val;
    while(root != null){
        // 如果该节点的离目标更近,则更新到目前为止的最近值
        closest = Math.abs(closest - target) < Math.abs(root.val - target) ? closest : root.val;
        // 二叉搜索
        root = target < root.val ? root.left : root.right;
    }

    return closest;
}

results matching ""

    No results matching ""