-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
35 lines (32 loc) · 961 Bytes
/
Copy pathsolution.java
File metadata and controls
35 lines (32 loc) · 961 Bytes
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
class Solution {
public ArrayList<Node> findPreSuc(Node root, int key) {
Node pre = null, suc = null;
while (root != null) {
if (root.data < key) {
pre = root;
root = root.right;
} else if (root.data > key) {
suc = root;
root = root.left;
} else {
// Predecessor
Node temp = root.left;
while (temp != null) {
pre = temp;
temp = temp.right;
}
// Successor
temp = root.right;
while (temp != null) {
suc = temp;
temp = temp.left;
}
break;
}
}
ArrayList<Node> res = new ArrayList<>();
res.add(pre);
res.add(suc);
return res;
}
}