-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree.java
More file actions
118 lines (104 loc) · 2.32 KB
/
Binary_Tree.java
File metadata and controls
118 lines (104 loc) · 2.32 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
package Daily_Problem;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Binary_Tree {
static Queue<Integer> que=new LinkedList<>() ;
static class Node{
int data;
Node left;
Node right;
public Node(int num)
{
this.data=num;
this.left=null;
this.right=null;
}
}
static class BinaryTree
{
static int index=-1;
public static Node Buildtree(int arr[])
{
index++;
if(arr[index]==-1)
return null;
Node nn=new Node(arr[index]);
nn.left= Buildtree(arr);
nn.right= Buildtree(arr);
return nn;
}
}
public static void main(String[] args) {
int arr[] ={1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1};
BinaryTree obj=new BinaryTree();
Node ans= new Node(1);
ans.left=new Node(2);
ans.right=new Node(3);
ans.left.left=new Node(4);
ans.left.right=new Node(5);
ans.right.left=new Node(6);
ans.right.right=new Node(7);
System.out.println("PREORDER : ");
preorder(ans);
System.out.println();
System.out.println("POSTORDER : ");
postorder(ans);
System.out.println();
System.out.println("InOrder : ");
inorder(ans);
System.out.println();
System.out.println("LEVELORDER : ");
que.add(ans.data);
levelorder(ans);
System.out.println(que);
levelprint(1);
}
private static void levelprint(int n) {
for(int i=0;i<n;i++)
{
if(que.isEmpty())
return;
System.out.print(que.poll()+ " ");
}
System.out.println();
levelprint(n*2);
}
private static void levelorder(Node ans) {
if(ans.left!=null)
{
que.add(ans.left.data);
}
else
return;
if(ans.right!=null)
{
que.add(ans.right.data);
}
else
return;
levelorder(ans.left);
levelorder(ans.right);
}
private static void inorder(Node ans) {
if(ans==null)
return;
inorder(ans.left);
System.out.print(ans.data+" ");
inorder(ans.right);
}
private static void postorder(Node ans) {
if(ans==null)
return;
postorder(ans.left);
postorder(ans.right);
System.out.print(ans.data+" ");
}
private static void preorder(Node ans) {
if(ans==null)
return;
System.out.print(ans.data+" ");
preorder(ans.left);
preorder(ans.right);
}
}