0270. Closest Binary Search Tree Value

https://leetcode.com/problems/closest-binary-search-tree-value

Description

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

Example 1:

**Input:** root = [4,2,5,1,3], target = 3.714286
**Output:** 4

Example 2:

**Input:** root = [1], target = 4.428571
**Output:** 1

Constraints:

  • The number of nodes in the tree is in the range [1, 104].

  • 0 <= Node.val <= 109

  • -109 <= target <= 109

ac

/**
 * 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 res = root.val;

        while (root != null) {
            res = Math.abs(target - res) < Math.abs(target - root.val) ? res : root.val;

            if (target == root.val) {
                break;
            } else if (target < root.val) {
                root = root.left;
            } else {
                root = root.right;
            }
        }

        return res;
    }
}

Last updated