-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLevelTraversing.java
51 lines (41 loc) · 1.4 KB
/
LevelTraversing.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
package com.anudev.ds.trees;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class LevelTraversing {
public static void nonRecursiveLevelTraversal(Node node) {
System.out.print("Non recursive Level order traversal: ");
Queue<Node> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
Node pollNode = queue.poll();
System.out.print(pollNode.getValue() + ",");
// add left child
if (pollNode.getLeftNode() != null) {
queue.add(pollNode.getLeftNode());
}
// add right child
if (pollNode.getRightNode() != null) {
queue.add(pollNode.getRightNode());
}
}
}
public static ArrayList<Node> getLevelOrderedString(Node node) {
ArrayList<Node> list = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
Node pollNode = queue.poll();
list.add(pollNode);
// add left child
if (pollNode.getLeftNode() != null) {
queue.add(pollNode.getLeftNode());
}
// add right child
if (pollNode.getRightNode() != null) {
queue.add(pollNode.getRightNode());
}
}
return list;
}
}