270 Closest Binary Search Tree Value
270. Closest Binary Search Tree Value
1.Question
2. Implementation
class Solution {
public int closestValue(TreeNode root, double target) {
TreeNode curNode = root;
int res = root.val;
while (curNode != null) {
if (curNode.val == target) {
return curNode.val;
}
else if (Math.abs(curNode.val - target) < Math.abs(res - target)) {
res = curNode.val;
}
curNode = curNode.val < target ? curNode = curNode.right : curNode.left;
}
return res;
}
}3. Time & Space Complexity
Previous298 Binary Tree Longest Consecutive SequenceNext549 Binary Tree Longest Consecutive Sequence II
Last updated