[LeetCode] 270. 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.

Thought process:
Record root.val and recursively search for the closest value:
  1. If root.val < target, search in the right sub-tree. If abs(result - target) < abs(root.val - target), return result.
  2. If root.val >= target, search in the left sub-tree. If abs(result - target) < abs(root.val - target), return result.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * 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 closest = root.val;
        if (root.val < target) {
            if (root.right != null) {
                int right = closestValue(root.right, target);
                if (Math.abs(right - target) < Math.abs(closest - target)) {
                    closest = right;
                }
            }
        } else {
            if (root.left != null) {
                int left = closestValue(root.left, target);
                if (Math.abs(left - target) < Math.abs(closest - target)) {
                    closest = left;
                }
            }
        }
        return closest;
    }
}

Time complexity: O(logn).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee