-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathLevelOrderTraversal.java
101 lines (92 loc) · 2.51 KB
/
LevelOrderTraversal.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
package SummerTrainingGFG.Tree;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Vishal Singh
*/
public class LevelOrderTraversal {
static class Node{
int key;
Node left;
Node right;
Node(int key){
this.key = key;
}
}
/**
* Single Line*/
static void printLevel(Node root){
if (root == null){
return;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()){
Node curr = q.poll();
System.out.print(curr.key+" ");
if (curr.left != null)
q.add(curr.left);
if (curr.right != null)
q.add(curr.right);
}
}
/**
* Prinitng line by line - Method 1*/
static void lineByLineMeth1(Node root){
if (root == null)
return;
Queue<Node> q = new LinkedList<>();
q.add(root);
q.add(null);
while (q.size() > 1){
Node curr = q.poll();
if (curr == null){
System.out.println("");
q.add(null);
continue;
}
System.out.print(curr.key+" ");
if (curr.left != null){
q.add(curr.left);
}
if (curr.right != null){
q.add(curr.right);
}
}
}
/**
* Prinitng line by line - Method 2*/
static void lineByLineMeth2(Node root){
if (root == null)
return;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()){
int s = q.size();
for (int i = 0; i < s; i++) {
Node curr = q.poll();
System.out.print(curr.key+" ");
if (curr.left != null){
q.add(curr.left);
}
if (curr.right != null){
q.add(curr.right);
}
}
System.out.println();
}
}
public static void main(String[] args) {
Node root = new Node(10);
root.left = new Node(20);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right = new Node(30);
System.out.println("Printing on same line");
printLevel(root);
System.out.println("\nPrinitng line by line");
lineByLineMeth1(root);
System.out.println("\nPrinitng line by line Method 2");
lineByLineMeth2(root);
}
}