-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClosest Number In Binary Search Tree.java
116 lines (88 loc) · 2.14 KB
/
Closest Number In Binary Search Tree.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
In a binary search tree, find the node containing the closest number to the given target number.
Assumptions:
The given root is not null.
There are no duplicate keys in the binary search tree.
Examples:
5
/ \
2 11
/ \
6 14
closest number to 4 is 5
closest number to 10 is 11
closest number to 6 is 6
How is the binary tree represented?
We use the level order traversal sequence with a special symbol "#" denoting the null node.
For Example:
The sequence [1, 2, 3, #, #, 4] represents the following binary tree:
1
/ \
2 3
/
4
time = O(height) = O(n)
space = O(1)
*/
/**
* public class TreeNode {
* public int key;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int key) {
* this.key = key;
* }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
// write your code here
int closest = root.key;
while (root != null) {
if (root.key == target) {
return root.key;
}
if (Math.abs(root.key- target) < Math.abs(closest - target)) {
closest = root.key;
}
if (root.key < target) {
root = root.right;
} else {
root = root.left;
}
}
return closest;
}
}
// leetcode version
/**
* 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) {
if (root == null) {
return 0;
}
int result = root.val;
while (root != null) {
if (root.val == target) {
return root.val;
}
if (Math.abs(root.val - target) < Math.abs(result - target)) {
result = root.val;
}
if (root.val < target) {
root = root.right;
} else {
root = root.left;
}
}
return result;
}
}