题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
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> levelOrder (TreeNode root) { // write code here Queue queue=new LinkedList<>(); ArrayList<ArrayList> res=new ArrayList<>(); if(root==null){ return res; } queue.offer(root); while(!queue.isEmpty()){ ArrayList temp=new ArrayList<>(); int len=queue.size(); for(int i=0;i<len;i++){ TreeNode cur=queue.poll(); if(cur.left!=null){ queue.offer(cur.left); } if(cur.right!=null){ queue.offer(cur.right); } temp.add(cur.val); } res.add(temp); } return res; } }//运用队列先进先出的特性,将每一层的节点先保存下来,而后添加到列表中。