题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
import java.util.*;
/*
- 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>> lList = new ArrayList();
if(root == null){
return lList;
}
Queue<treenode> queue = new LinkedList();
queue.add(root);
while(!queue.isEmpty()){
ArrayList list = new ArrayList();
int count = queue.size();
while(count-- > 0){
TreeNode temp = queue.poll();
list.add(temp.val);
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
}
lList.add(list);
}
return lList;
}
}</treenode></integer></integer>