题解 | #求二叉树的层序遍历#队列实现
求二叉树的层序遍历
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) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); ArrayList<Integer> al = null; LinkedList<TreeNode> queue = new LinkedList<>(); if( root == null ) return res; queue.add(root); while( !queue.isEmpty()){ al = new ArrayList<>(); int size = queue.size(); for(int i=0;i<size;i++){ TreeNode node = queue.removeFirst(); al.add(node.val); if( node.left != null ){ queue.add(node.left); } if( node.right != null ){ queue.add(node.right); } } res.add(al); } return res; } }