forked from jvm-coder/Java_Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeTraversals.java
More file actions
92 lines (62 loc) · 1.7 KB
/
TreeTraversals.java
File metadata and controls
92 lines (62 loc) · 1.7 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
89
90
91
92
class Node{
int key;
Node left;
Node right;
public Node(int key){
this.key = key;
this.left = null;
this.right = null;
}
}
class BinaryTree{
public void InOrderTraversal(Node root){
if(root == null){
return;
}
InOrderTraversal(root.left);
System.out.print(root.key + " ");
InOrderTraversal(root.right);
}
public void PreOrderTraversal(Node root){
if(root == null){
return;
}
System.out.print(root.key + " ");
PreOrderTraversal(root.left);
PreOrderTraversal(root.right);
}
public void PostOrderTraversal(Node root){
if(root == null){
return;
}
PostOrderTraversal(root.left);
PostOrderTraversal(root.right);
System.out.print(root.key + " ");
}
}
public class TreeTraversals {
public static void main(String[] args) {
Node root = new Node(3);
root.left = new Node(2);
root.left.left = new Node(1);
root.right = new Node(4);
root.right.right = new Node(5);
/*
3
/ \
2 4
/ \
1 5
*/
BinaryTree bt = new BinaryTree();
System.out.print("InOrderTraversal of the Binary Tree : ");
bt.InOrderTraversal(root);
System.out.println("");
System.out.print("PreOrderTraversal of the Binary Tree : ");
bt.PreOrderTraversal(root);
System.out.println("");
System.out.print("PostOrderTraversal of the Binary Tree : ");
bt.PostOrderTraversal(root);
System.out.println("");
}
}