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

求二叉树的层序遍历

https://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
           // write code here
        ArrayList<ArrayList<Integer>> list=new ArrayList<>();
        TreeNode cursor_1=root;
        if(cursor_1==null){
            return list;
        }
        Deque<TreeNode> deque=new LinkedList<>();
        deque.push(cursor_1);
        int length=1;
        while(!deque.isEmpty()){
            int num=0;
            int nextlength=0;
            ArrayList<Integer> sublist=new ArrayList<>();
            while(num<length&&(!deque.isEmpty())){
                cursor_1=deque.poll();
                sublist.add(cursor_1.val);
                if(cursor_1.left!=null){
                    deque.addLast(cursor_1.left);
                    nextlength++;
                }
                if(cursor_1.right!=null){
                    deque.addLast(cursor_1.right);
                    nextlength++;
                }
                num++;
                
            }
            list.add(sublist);
            length=nextlength;
        }
        return list;
    }
}

全部评论

相关推荐

我在朝九晚六双休的联想等你:如果我是你,身体素质好我会去参军,然后走士兵计划考研211只需要200多分。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务