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.
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
Stack<TreeNode> stk = new Stack<TreeNode>();
TreeNode cur = root;
TreeNode pre = null;
while (!stk.isEmpty() || cur != null) {
if (cur != null) {
stk.push(cur);
cur = cur.left;
} else {
TreeNode node = stk.pop();
// visit
if (target < node.val) {
if (pre == null) return node.val;
else {
return Math.abs(node.val - target) > Math.abs(pre.val - target) ? pre.val : node.val;
}
}
pre = node;
cur = node.right;
}
}
return pre.val;
}
}
================
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
TreeNode cur = root;
TreeNode res = root;
while (cur != null) {
if (Math.abs(cur.val - target) < Math.abs(res.val - target)) {
res = cur;
}
if (cur.val > target) {
cur = cur.left;
} else {
cur = cur.right;
}
}
return res.val;
}
}
没有评论:
发表评论