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.

思路

  • if target < a, then the closest value is a or some value from tree b
  • if target > a, then the closest value is a or some value from tree c
    public int closestValue(TreeNode root, double target) {
        TreeNode child = root.val < target ? root.right : root.left;
        if (child == null) return root.val;
        int val = closestValue(child, target);
        return Math.abs(root.val - target) > Math.abs(val - target) ? val : root.val;
    }

results matching ""

    No results matching ""