-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0102_Binary_Tree_Level_Order_Traversal.java
42 lines (37 loc) · 1.16 KB
/
0102_Binary_Tree_Level_Order_Traversal.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
/*
* 102. Binary Tree Level Order Traversal
* Problem Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
if (root != null) {
q.add(root);
}
List<List<Integer>> result = new ArrayList<>();
while (!q.isEmpty()){
// number of nodes at this leveel
int count = q.size();
List<Integer> list = new ArrayList<>(q.size());
while (count > 0) {
root = q.poll();
list.add(root.val);
if (root.left != null) {
q.add(root.left);
}
if (root.right != null) {
q.add(root.right);
}
count--;
}
result.add(list);
}
return result;
}
}