题目
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] ]
层遍历,从左到右
1 基本的基本,广度遍历,要写的熟练。
2 容易出错的地方 a queue不要写成stack b queue的函数是add 和remove c 计数器何时使用 d 每次添加要new ArrayList 和clear一下
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
if(root==null){
return ans;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int num =0;
int count =1;
while(!queue.isEmpty()){
TreeNode cur = queue.remove();
temp.add(cur.val);
count--;
if(cur.left!=null){
queue.add(cur.left);
num++;
}
if(cur.right!=null){
queue.add(cur.right);
num++;
}
if(count==0){
ans.add(new ArrayList<Integer>(temp));
temp.clear();
count = num;
num =0;
}
}
return ans;
}
}