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.
Example:
Input: root = [4,2,5,1,3], target = 3.714286
4
/ \
2 5
/ \
1 3
Output: 4
ไปฃ็
Approach #1 Recursive Inorder O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicintclosestValue(TreeNode root,double target) {List<Integer> nums =newArrayList();inorder(root, nums);returnCollections.min(nums,newComparator<Integer>() { @Overridepublicintcompare(Integer o1,Integer o2) {returnMath.abs(o1 - target) -Math.abs(o2 - target); } }); }privatevoidinorder(TreeNode root,List<Integer> nums) {if (root ==null) return;inorder(root.left, nums);nums.add(root.val);inorder(root.right, nums); }}