-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Tree_Traversals.java
70 lines (52 loc) · 1.62 KB
/
Binary_Tree_Traversals.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
public class BinaryTreeTraversal {
int item;
BinaryTreeTraversal left, right;
public BinaryTreeTraversal(int key) {
item = key;
left = right = null;
}
}
class BinaryTree {
BinaryTreeTraversal root;
BinaryTree() {
root = null;
}
void post_order(BinaryTreeTraversal node) {
if (node == null)
return;
post_order(node.left);
post_order(node.right);
System.out.print(node.item + " ");
}
void inorder(BinaryTreeTraversal node) {
if (node == null)
return;
inorder(node.left);
System.out.print(node.item + " ");
inorder(node.right);
}
void pre_order(BinaryTreeTraversal node) {
if (node == null)
return;
System.out.print(node.item + " ");
pre_order(node.left);
pre_order(node.right);
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new BinaryTreeTraversal(4);
tree.root.left = new BinaryTreeTraversal(23);
tree.root.right = new BinaryTreeTraversal(13);
tree.root.left.left = new BinaryTreeTraversal(7);
tree.root.left.right = new BinaryTreeTraversal(11);
System.out.println("The Inorder traversal of the Binary Tree is : ");
tree.inorder(tree.root);
System.out.println(" ");
System.out.println("\nThe Preorder traversal of the Binary Tree is : ");
tree.pre_order(tree.root);
System.out.println(" ");
System.out.println("\nThe Postorder traversalof the Binary Tree is : ");
tree.post_order(tree.root);
System.out.println(" ");
}
}