-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_6.java
More file actions
69 lines (57 loc) · 1.61 KB
/
Copy pathProblem_6.java
File metadata and controls
69 lines (57 loc) · 1.61 KB
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
package trees.binarySearchTree;
import java.util.ArrayList;
// Problem Title => Populate Inorder Successor for all nodes
public class Problem_6 {
static class Node {
int data;
Node left, right, next;
Node(int data) {
this.data = data;
left = right = next = null;
}
}
Node root;
ArrayList<Node> list = new ArrayList<>();
void populateNext() {
for (int i = 0; i < list.size(); i++) {
if (i != list.size() - 1)
list.get(i).next = list.get(i + 1);
else
list.get(i).next = null;
}
Node ptr = root.left.left;
while (ptr != null) {
// -1 is printed if there is no successor
int print = ptr.next != null ? ptr.next.data : -1;
System.out.println("Next of " + ptr.data + " is: " + print);
ptr = ptr.next;
}
}
// insert the inorder into a linkedList.list to keep track of the inorder
// successor
void inorder(Node root) {
if (root != null) {
inorder(root.left);
list.add(root);
inorder(root.right);
}
}
// Driver function
public static void main(String[] args) {
Problem_6 tree = new Problem_6();
/*
* 10
* / \
* 8 12
* /
* 3
*/
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.right = new Node(12);
tree.root.left.left = new Node(3);
// function calls
tree.inorder(tree.root);
tree.populateNext();
}
}