-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelOrderBinaryTree
35 lines (34 loc) · 967 Bytes
/
LevelOrderBinaryTree
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> answer = new LinkedList<>();
if(root==null)
return answer;
Queue<TreeNode> cache = new LinkedList<>();
cache.add(root);
while(!cache.isEmpty())
{
List<Integer> currLevel = new LinkedList<>();
int n = cache.size();
for(int i =0;i<n;i++)
{
TreeNode temp=cache.poll();
currLevel.add(temp.val);
if(temp.left!=null)
cache.add(temp.left);
if(temp.right!=null)
cache.add(temp.right);
}
answer.add(currLevel);
}
return answer;
}
}