-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevelOrderBFS.java
More file actions
56 lines (44 loc) · 1.28 KB
/
LevelOrderBFS.java
File metadata and controls
56 lines (44 loc) · 1.28 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
package Trees;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class LevelOrderBFS {
/*
* Breadth First Search algorithm to find and print the elements in level order.
*/
public static void bfs(Node root) {
Queue<Node> q = new LinkedList<>();
if (root != null)
q.add(root);
while (q.size() > 0) {
Node temp = q.peek();
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
System.out.print(temp.val + " ");
q.poll();
}
}
public static void reverseLevelOrder(Node root) {
Stack<Node> stack = new Stack<>();
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node temp = queue.poll();
stack.push(temp);
if (temp.right != null) {
queue.add(temp.right);
}
if (temp.left != null) {
queue.add(temp.left);
}
}
while (!stack.isEmpty()) {
Node temp = stack.pop();
System.out.print(temp.val + " ");
}
}
public static void main(String[] args) {
}
}