forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevelOrderbtree.java
More file actions
115 lines (103 loc) · 2.62 KB
/
Copy pathlevelOrderbtree.java
File metadata and controls
115 lines (103 loc) · 2.62 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
import java.util.Queue;
import java.util.*;
class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = right = null;
}
}
class BinaryTree {
Node root;
BinaryTree() {
root = null;
}
BinaryTree(int data) {
this.root = new Node(data);
}
int height(Node root) {
if (root == null)
return -1;
return 1 + Math.max(height(root.left), height(root.right));
}
void printAtLevel(Node root, int level) {
if (root == null)
return;
if (level == 1) {
System.out.print(root.data + " ");
return;
}
printAtLevel(root.left, level - 1);
printAtLevel(root.right, level - 1);
}
void levrec(Node root) {
if (root == null)
return;
int h = height(root);
for (int i = 1; i <= h + 1; i++) {
printAtLevel(root, i);
System.out.println();
}
}
// iterative method single line
void levitr(Node root) {
if (root == null) {
return;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
Node temp = q.remove();
System.out.print(temp.data + " ");
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
}
System.out.println();
}
// iterative level wise
void levlineitr(Node root)
{
if (root == null)
return;
Queue<Node> q = new java.util.LinkedList<>();
q.add(root);
while (true) {
int size = q.size();
if (size == 0)
break;
// while(size>0)
for (int i = 0; i < size; i++)
{
Node temp = q.remove();
System.out.print(temp.data + " ");
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
// size--;
}
System.out.println();
}
}
}
class levelOrderbtree {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree(2);
bt.root.left = new Node(3);
bt.root.right = new Node(5);
bt.root.left.right = new Node(9);
bt.root.right.left = new Node(7);
bt.levrec(bt.root);
// iterative
bt.levitr(bt.root);
bt.levlineitr(bt.root);
}
}