Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Answer:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null)return res;
List<Integer> subres = new ArrayList<Integer>();
int pushnum=0, popnum=1;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
while(!que.isEmpty()){
TreeNode cur = que.peek();
que.poll();
popnum--;
subres.add(cur.val);
if(cur.left!=null){
que.add(cur.left);
pushnum++;
}
if(cur.right!=null){
que.add(cur.right);
pushnum++;
}
if(popnum==0){
int tmp=pushnum;
pushnum = popnum;
popnum = tmp;
res.add(subres);
}
}
return res;
}
}