-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Creations.java
More file actions
132 lines (125 loc) · 3.27 KB
/
Binary_Tree_Creations.java
File metadata and controls
132 lines (125 loc) · 3.27 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package Daily_Problem.Trees;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Binary_Tree_Creations {
static class Node {
int data;
Node left;
Node right;
public Node(int num) {
this.data = num;
this.left = null;
this.right = null;
}
}
static int idx = -1;
public static Node buildtree(int[] arr) {
idx++;
if (arr[idx] == -1) {
return null;
}
Node nn = new Node(arr[idx]);
nn.left = buildtree(arr);
nn.right = buildtree(arr);
return nn;
}
public static void preorder(Node nn) {
if (nn == null)
return;
System.out.print(nn.data + " ");
preorder(nn.left);
preorder(nn.right);
}
public static void inorder(Node nn) {
if (nn == null)
return;
inorder(nn.left);
System.out.print(nn.data + " ");
inorder(nn.right);
}
public static void postorder(Node nn) {
if (nn == null)
return;
postorder(nn.left);
postorder(nn.right);
System.out.print(nn.data + " ");
}
public static void levelorder(Node nn) {
if(nn==null)
return;
Queue<Node> q=new LinkedList<>();
q.add(nn);
while(!q.isEmpty())
{
Node n=q.poll();
System.out.print(n.data+" ");
if(n.left!=null)
{
q.add(n.left);
}
if(n.right!=null) {
q.add(n.right);
}
}
}
public static List<List<Integer>> zigzag(Node nn)
{
List<List<Integer>> ans=new LinkedList<>();
if(nn==null)
return ans;
Queue<Node> q=new LinkedList<>();
q.add(nn);
boolean b=true;
while(!q.isEmpty())
{
int size=q.size();
List<Integer> l=new LinkedList<>();
for (int i=0;i<size;i++)
{
Node n=q.poll();
l.add(n.data);
if(n.left!=null)
{
q.add(n.left);
}
if(n.right!=null) {
q.add(n.right);
}
}
if(!b) {
Collections.reverse(l);
}
ans.add(l);
b = !b;
}
return ans;
}
public static void print(List<List<Integer>> ans)
{
for(List<Integer> i:ans)
{
for(int j:i)
{
System.out.print(j+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1};
Node root = buildtree(arr);
preorder(root);
System.out.println();
inorder(root);
System.out.println();
postorder(root);
System.out.println();
System.out.print("Level Order : ");
levelorder(root);
System.out.println();
List<List<Integer>> ans= zigzag(root);
print(ans);
}
}