-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBinaryTree_Aman.java
More file actions
112 lines (91 loc) · 2.56 KB
/
Copy pathBinaryTree_Aman.java
File metadata and controls
112 lines (91 loc) · 2.56 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package trees;
import java.util.*;
public class BinaryTree_Aman {
private static Node root;
private static class Node {
private int data;
Node left, right;
@SuppressWarnings("unused")
Node(int d) {
this.data = d;
left = right = null;
}
}
// Problem 1 -> Level Order Traversal
public static void levelOrder() {
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
Node temp = q.poll();
System.out.println(temp.data + " ");
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
}
}
// Problem 2 -> Reverse Level Order Traversal
public static void reverseLevelOrder() {
// Implementation using stacks and queues provided above
}
// Inorder Traversal of Binary Tree
public static void inOrder() {
if (root == null)
return;
Stack<Node> s = new Stack<>();
Node curr = root;
while (curr != null || s.size() > 0) {
while (curr != null) {
s.push(curr);
curr = curr.left;
}
}
curr = s.pop();
System.out.print(curr.data + " ");
/*
* we have visited the node and its left subtree.
* Now, its right subtree's turn
*/
curr = curr.right;
}
// Recursive Inorder Traversal of Binary Tree
public static void recursiveInOrder(Node node) {
if (node == null)
return;
recursiveInOrder(node.left);
System.out.println(node.data + " ");
recursiveInOrder(node.right);
}
// Wrapper for recursive inorder
void recursiveInOrder() {
recursiveInOrder(root);
}
// Preorder Traversal of Binary Tree using recursion
public static void preOrder(Node node) {
if (node == null)
return;
System.out.println(node.data);
preOrder(node.left);
preOrder(node.right);
}
// Wrapper for preorder
void preOrder() {
preOrder(root);
}
// Preorder Traversal of Binary Tree
public static void postOrder(Node root) {
if (root == null)
return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + " ");
}
// Wrapper for Post Order
void postOrder() {
postOrder(root);
}
public static void main(String[] args) {
}
}