-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClosestBinarySearchTreeValue.java
More file actions
40 lines (34 loc) · 1.09 KB
/
ClosestBinarySearchTreeValue.java
File metadata and controls
40 lines (34 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package binary_search_tree;
import java.util.Deque;
import java.util.LinkedList;
/**
* Description: https://leetcode.com/problems/closest-binary-search-tree-value
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class ClosestBinarySearchTreeValue {
public int closestValueViaInorderTraversal(TreeNode root, double target) {
int predecessor = Integer.MIN_VALUE;
Deque<TreeNode> stack = new LinkedList<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
if (predecessor <= target && target <= root.val) {
return Math.abs(predecessor - target) <= Math.abs(root.val - target) ? predecessor : root.val;
}
predecessor = root.val;
root = root.right;
}
}
return predecessor;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}