-
Notifications
You must be signed in to change notification settings - Fork 0
/
InorderPreSucOfAGivenKeyInBST.java
82 lines (70 loc) · 2.12 KB
/
InorderPreSucOfAGivenKeyInBST.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 Practice;
public class InorderPreSucOfAGivenKeyInBST {
class Node{
int data;
Node left,right;
Node(int data){
this.data = data;
this.left = this.right = null;
}
}
static Node pre, suc;
public Node insert(Node root, int key){
if(root == null)
return new Node(key);
if(key < root.data){
root.left = insert(root.left, key);
}else {
root.right = insert(root.right, key);
}
return root;
}
public static void main(String[] args) {
InorderPreSucOfAGivenKeyInBST x = new InorderPreSucOfAGivenKeyInBST();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80
*/
Node root = null;
int[] keys = new int[]{50,30,20,40,70,60,80};
for(int each:keys){
root = x.insert(root, each);
}
int key = 11; // Key to be searched in BST
preSuc(root, key);
System.out.println("Predecessor: " + ((pre== null)?-1:pre.data));
System.out.println("Successor: " + ((suc== null)?-1:suc.data));
}
private static void preSuc(Node root, int key) {
if(root == null)
return;
while(root != null){
if(root.data == key){
if(root.left != null){
pre = root.left;
while(pre.right != null){
pre = pre.right;
}
}
if(root.right != null){
suc = root.right;
while(suc != null){
suc = suc.left;
}
}
return;
}else if(root.data != key){
if(key < root.data){
suc = root;
root = root.left;
}else{
pre = root;
root = root.right;
}
}
}
}
}