leetcode102 二叉树

102.png
    public List> levelOrder(TreeNode root) {
        ArrayList> res = new ArrayList<>();
        if(root == null)
            return res;
        Queue queue = new LinkedList<>();
        queue.add(root);
        int levelNum = 1;
        while(!queue.isEmpty()){
            int newLevelNum = 0;
            ArrayList level = new ArrayList<>();
            for(int i = 0; i < levelNum; i ++){
                TreeNode node = queue.remove();
                level.add(node.val);

                if(node.left != null){
                    queue.add(node.left);
                    newLevelNum ++;
                }
                if(node.right != null){
                    queue.add(node.right);
                    newLevelNum ++;
                }
            }
            res.add(level);
            levelNum = newLevelNum;
        }
        return res;
    }

你可能感兴趣的:(leetcode102 二叉树)