270. Closest Binary Search Tree Value

Problem:
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.
8/19/2018 update:
如果root.val > target, 说明了root的右边肯定离target更远,所以要往左走。
--------------------------------------------------------------------------------------------------------------------------------------------

Analysis:
The result is updated by the smaller different between current node's val and target. 
Solution:

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 = root.val > target ? root.left : root.right;
        }
        return res;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array