-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInorderSuccessor.java
84 lines (76 loc) · 2.49 KB
/
InorderSuccessor.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
package com.anudev.ds.trees;
public class InorderSuccessor {
public static void printInorderSuccessor(Node rootNode, int key) {
Node node = findNode(rootNode, key);
if (node == null) {
System.out.println("Invalid key");
return;
}
// if the right node is not null then the node which is having
// smallest value in the left subtree is the inorder successor
// of the node value
Node successorFound;
if (node.getRightNode() != null) {
successorFound = findSmallestValueOfTree(node.getRightNode());
}
// if the left node is not present then the node where we
// have taken last right while reaching the key node is the
// inorder predecessor
else {
successorFound = findLastLeftNode(rootNode, key);
}
if (successorFound != null) {
System.out.print("Successor of node " + key + " is " + successorFound.getValue());
} else {
System.out.print("No successor of node ");
}
}
private static Node findNode(Node rootNode, int key) {
Node node = rootNode;
Node keyNode = null;
while (true) {
if (node == null) {
break;
} else if (node.getValue() == key) {
keyNode = node;
break;
} else if (node.getValue() > key) {
node = node.getLeftNode();
} else {
node = node.getRightNode();
}
}
return keyNode;
}
// find the smallest value in subtree
private static Node findSmallestValueOfTree(Node node) {
while (node.getLeftNode() != null) {
node = node.getLeftNode();
}
return node;
}
// find last left node
private static Node findLastLeftNode(Node rootNode, int key) {
Node node = rootNode;
boolean found = false;
Node lastLeftNode = null;
while (true) {
if (node == null) {
break;
} else if (node.getValue() == key) {
found = true;
break;
} else if (node.getValue() > key) {
lastLeftNode = node;
node = node.getLeftNode();
} else {
node = node.getRightNode();
}
}
// if the element is found then
if (found) {
return lastLeftNode;
}
return null;
}
}