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 {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]跟 Binary Tree Level Order Traversal II相比,就是添加的位置不同,把list.add(0,tmp) 改成list.add(tmp)就OK
/**
* 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>> list = new LinkedList<List<Integer>>();//返回结果
Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列,使用BFS遍历
int level = 0;//记录某一层进队的元素数
int count = 0;//计数
if(root == null){
return list;
}
queue.offer(root);
level++;
TreeNode p = null;
while(queue.size() > 0){
int nextLevel = 0;//下一层进队的元素数
List<Integer> tmp = new ArrayList<Integer>();//中间存储每一行的结果
while(count < level){
p = queue.poll();//出队
if(p.left != null){
queue.offer(p.left);
nextLevel++;
}
if(p.right != null){
queue.offer(p.right);
nextLevel++;
}
tmp.add(p.val);
count ++;
}
list.add(tmp);
count = 0;
level = nextLevel;
}
return list;
}
}
Runtime: 244 ms