题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

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;
    }
}
全部评论

相关推荐

我要娶个什么名:学长你电脑闹鬼了
点赞 评论 收藏
分享
牛客77743221...:做一段时间,公司出钱送你去缅甸和泰国旅游
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务