-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLevelOrderTraversal.java
61 lines (53 loc) · 1.53 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
/*
recursively find the total number of nodes in a binary tree.(asked in my university exam)
Example:
root=[1,2,3]
output=3
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class LevelOrderTraversal {
public static void main(String[] args) {
Node1 root = new Node1(1);
root.left = new Node1(2);
root.right = new Node1(3);
System.out.println(BFSTraversal(root));
}
public static int BFSTraversal(Node1 root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return 0;
}
Queue<Node1> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelsize = queue.size();
for (int i = 0; i < levelsize; i++) {
Node1 cur = queue.poll();
if (cur.left != null) {
queue.offer(cur.left);
result.add(cur.left.data);
BFSTraversal(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
result.add(cur.right.data);
BFSTraversal(cur.right);
}
}
}
return result.size() + 1;
}
}
// nodes of the tree
class Node1 {
int data;
Node1 left, right;
public Node1(int key) {
key = data;
left = null;
right = null;
}
}