-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_00.java
More file actions
88 lines (68 loc) · 2.17 KB
/
Copy pathBinary_Tree_00.java
File metadata and controls
88 lines (68 loc) · 2.17 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public class Binary_Tree_00 {
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
static class Binary_Tree {
int idx = -1;
// Build Tree from given Preorder Sequence
public Node Build_Tree(int[] Preorder) {
idx++;
if (Preorder[idx] == -1) {
return null;
}
Node new_Node = new Node(Preorder[idx]);
new_Node.left = Build_Tree(Preorder);
new_Node.right = Build_Tree(Preorder);
return new_Node;
}
// Preorder_Traversal
public void Preorder_Traversal(Node Root) {
if (Root == null) {
return;
}
System.out.print(Root.data + " ");
Preorder_Traversal(Root.left);
Preorder_Traversal(Root.right);
}
// Inorder_Traversal
public void Inorder_Traversal(Node Root) {
if (Root == null) {
return;
}
Preorder_Traversal(Root.left);
System.out.print(Root.data + " ");
Preorder_Traversal(Root.right);
}
// Postorder_Traversal
public void Postorder_Traversal(Node Root) {
if (Root == null) {
return;
}
Preorder_Traversal(Root.left);
Preorder_Traversal(Root.right);
System.out.print(Root.data + " ");
}
}
public static void main(String[] args) {
int[] Preorder = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1 };
Binary_Tree tree = new Binary_Tree();
Node Root = tree.Build_Tree(Preorder);
System.out.println(Root.data);
System.out.println("Preorder_Traversal: ");
tree.Preorder_Traversal(Root);
System.out.println();
System.out.println("Inorder_Traversal: ");
tree.Inorder_Traversal(Root);
System.out.println();
System.out.println("Postorder_Traversal: ");
tree.Postorder_Traversal(Root);
System.out.println();
}
}