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
最接近的二叉搜索树的值。题意是给一个二叉树和一个target值(会是一个浮点数),请找出二叉树里面val最接近这个target的node。
递归的思路我没有想得非常清楚所以我这里只给出迭代的做法。因为是BST所以会简单很多,根据target与root节点比较的大小情况来决定到底往左子树走还是往右子树走。
时间O(logn) - 因为每次只会往树的一边走
空间 - O(1)
Java实现
1 class Solution { 2 public int closestValue(TreeNode root, double target) { 3 int res = root.val; 4 while (root != null) { 5 if (Math.abs(target - root.val) < Math.abs(target - res)) { 6 res = root.val; 7 } 8 root = root.val > target ? root.left : root.right; 9 } 10 return res; 11 } 12 }
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @param {number} target 4 * @return {number} 5 */ 6 var closestValue = function (root, target) { 7 let res = root.val; 8 while (root !== null) { 9 if (Math.abs(root.val - target) < Math.abs(res - target)) { 10 res = root.val; 11 } 12 root = root.val > target ? root.left : root.right; 13 } 14 return res; 15 };