Closed congr closed 5 years ago
Iterative
/**
* 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) {
TreeNode closest = root;
while (root != null) {
double cur = Math.abs(root.val - target);
double pre = Math.abs(closest.val - target);
if (cur < pre) closest = root;
if (root.val < target) root = root.right;
else if (root.val > target) root = root.left;
else return root.val;
}
return closest.val;
}
}
Recursive
/**
* 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 val = root.val;
if (root.val > target && root.left != null) val = closestValue(root.left, target);
else if (root.val < target && root.right != null) val = closestValue(root.right, target);
return Math.abs(root.val - target) < Math.abs(val - target) ? root.val : val;
}
}
https://leetcode.com/problems/closest-binary-search-tree-value/