题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
ArrayList<ArrayList<Integer>> flours = new ArrayList<>();
if(root == null){
return flours;
}
TreeNode node = root;
Queue<TreeNode> q = new LinkedList<>();
q.offer(node);
while(!q.isEmpty()){
int size = q.size();
ArrayList<Integer> flour = new ArrayList<>();
for(int i = 0; i< size;i ++){
TreeNode cur = q.poll();
flour.add(cur.val);
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
}
flours.add(flour);
}
return flours;
}
}

