-
Notifications
You must be signed in to change notification settings - Fork 14
/
treeTraversals.java
121 lines (96 loc) · 2.87 KB
/
treeTraversals.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree {
static Scanner sc = new Scanner(System.in);
public static Node buildTree(Node head) {
int value = sc.nextInt();
if (value == -1) {
return null;
}
head = new Node(value);
// Left child
head.left = buildTree(head.left);
// Right child
head.right = buildTree(head.right);
return head;
}
// Level Order Traversal
public static void levelOrderTraversal(Node head) {
if (head == null) {
return;
}
Queue<Node> q = new LinkedList<>();
q.add(head);
q.add(null);
while (!q.isEmpty()) {
Node temp = q.poll();
if (temp != null) {
System.out.print(temp.data + " ");
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
} else {
System.out.println();
if (!q.isEmpty()) {
q.add(null);
}
}
}
}
// InOrder Traversal (Left - Node - Right)
public static void inOrder(Node head) {
if (head == null) {
return;
}
inOrder(head.left); // Left
System.out.print(head.data + " "); // Node
inOrder(head.right); // Right
}
// PreOrder Traversal (Node - Left - Right)
public static void preOrder(Node head) {
if (head == null) {
return;
}
System.out.print(head.data + " "); // Node
inOrder(head.left); // Left
inOrder(head.right); // Right
}
// PostOrder Traversal (Left - Right - Node)
public static void postOrder(Node head) {
if (head == null) {
return;
}
inOrder(head.left); // Left
inOrder(head.right); // Right
System.out.print(head.data + " "); // Node
}
public static void main(String[] args) {
// Example input: 1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 -1
Node root = null;
root = buildTree(root);
System.out.println("Level Order Traversal: ");
levelOrderTraversal(root);
System.out.println("InOrder Traversal: ");
inOrder(root);
System.out.println();
System.out.println("PreOrder Traversal: ");
preOrder(root);
System.out.println();
System.out.println("PostOrder Traversal: ");
postOrder(root);
System.out.println();
}
}