-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstruct a generic tree
93 lines (75 loc) · 1.82 KB
/
construct a generic tree
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
85
86
87
88
89
90
91
92
93
import java.util.*;
public class Main {
public static class Node {
int data;
Node left;
Node right;
Node() {
}
Node(int data) {
this.data = data;
}
}
public static class Pair {
Node node;
int state;
Pair() {
}
Pair(Node node, int state) {
this.node = node;
this.state = state;
}
}
public static Node construct(Integer[]arr) {
Node root = new Node(arr[0]);
Stack< Pair>st = new Stack< >();
Pair root_pair = new Pair(root, 1);
st.push(root_pair);
int idx = 1;
while (st.size() > 0) {
Pair top = st.peek();
if (top.state == 1) {
//waiting for left child
top.state++;
if (arr[idx] != null) {
Node lc = new Node(arr[idx]);
top.node.left = lc;
Pair lcp = new Pair(lc, 1);
st.push(lcp);
}
idx++;
}
else if (top.state == 2) {
//waiting for right child
top.state++;
if (arr[idx] != null) {
Node rc = new Node(arr[idx]);
top.node.right = rc;
Pair rcp = new Pair(rc, 1);
st.push(rcp);
}
idx++;
}
else if (top.state == 3) {
st.pop();
}
}
return root;
}
public static void display(Node node) {
if (node == null) {
return;
}
String str = " <- " + node.data + " -> ";
String left = (node.left == null) ? "." : "" + node.left.data;
String right = (node.right == null) ? "." : "" + node.right.data;
str = left + str + right;
System.out.println(str);
display(node.left);
display(node.right);
}
public static void main(String[]args) {
Integer[]arr = {50, 25, 12, null, null, 37, 30, null, null, null, 75, 62, null, 70, null, null, 87, null, null};
Node root = construct(arr);
}
}