-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay44.java
82 lines (70 loc) · 1.99 KB
/
Day44.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
package week6;
/* Predecessor and Successor */
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
public class Day44 {
static Node pre = null, suc = null;
public static void findPreSuc(Node root, int key) {
findPreSucUtil(root, key);
// Print the predecessor and successor values
System.out.println("Predecessor: " + (pre != null ? pre.data : "null"));
System.out.println("Successor: " + (suc != null ? suc.data : "null"));
}
private static void findPreSucUtil(Node root, int key) {
if (root == null) {
return;
}
// If key is present at root
if (root.data == key) {
// Finding predecessor
if (root.left != null) {
Node tmp = root.left;
while (tmp.right != null) {
tmp = tmp.right;
}
pre = tmp;
}
// Finding successor
if (root.right != null) {
Node tmp = root.right;
while (tmp.left != null) {
tmp = tmp.left;
}
suc = tmp;
}
return;
}
// If key is smaller than root's data, go to left subtree
if (key < root.data) {
suc = root;
findPreSucUtil(root.left, key);
}
// If key is greater than root's data, go to right subtree
else {
pre = root;
findPreSucUtil(root.right, key);
}
}
public static void main(String[] args) {
/*
4
/ \
2 5
/ \
1 3
*/
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
int key = 3;
findPreSuc(root, key);
}
}