题目
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
我的想法
最开始的想法是,当前结点的差值与左右子结点的差值比较,如果当前最小则输出当前,否则将当前结点设为较小的那个点,在继续循环。但是这样有个问题,当前最小并不一定是全局最小。因为BST是中序遍历,当前结点的前一个值不一定是左结点。
因此,后来改用中序遍历+打擂台。但是时间复杂度是O(n)
public class Solution {
public int closestValue(TreeNode root, double target) {
Deque<TreeNode> stack = new ArrayDeque<>();
double min = Integer.MAX_VALUE;
TreeNode minNode = root;
while(root != null) {
stack.push(root);
root = root.left;
}
while(!stack.isEmpty()) {
TreeNode cur = stack.pop();
double diff = Math.abs(cur.val - target);
if(min > diff) {
min = diff;
minNode = cur;
} else {
return minNode.val;
}
if(cur.right != null) {
cur = cur.right;
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
}
}
return minNode.val;
}
}
解答
jiuzhang solution:
求出 lowerBound 和 upperBound。即 < target 的最大值和 >= target 的最小值。
然后在两者之中去比较谁更接近,然后返回即可。时间复杂度会比中序遍历好一些
class Solution {
public int closestValue(TreeNode root, double target) {
if (root == null) {
return 0;
}
TreeNode lowerNode = lowerBound(root, target);
TreeNode upperNode = upperBound(root, target);
if (lowerNode == null) {
return upperNode.val;
}
if (upperNode == null) {
return lowerNode.val;
}
if (target - lowerNode.val > upperNode.val - target) {
return upperNode.val;
}
return lowerNode.val;
}
// find the node with the largest value that smaller than target
private TreeNode lowerBound(TreeNode root, double target) {
if (root == null) {
return null;
}
if (target <= root.val) {
return lowerBound(root.left, target);
}
// root.val < target
TreeNode lowerNode = lowerBound(root.right, target);
if (lowerNode != null) {
return lowerNode;
}
return root;
}
// find the node with the smallest value that larger than or equal to target
private TreeNode upperBound(TreeNode root, double target) {
if (root == null) {
return null;
}
if (root.val < target) {
return upperBound(root.right, target);
}
// root.val >= target
TreeNode upperNode = upperBound(root.left, target);
if (upperNode != null) {
return upperNode;
}
return root;
}
}