Java 3ms


  • 0
    J
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root == null) return result;
            ArrayList<TreeNode> level = new ArrayList<>();
            level.add(root);
            while (!level.isEmpty()) {
                ArrayList<Integer> levelRes = new ArrayList<>();
                ArrayList<TreeNode> nextLevel = new ArrayList<>();
                for (TreeNode node : level) {
                    levelRes.add(node.val);
                    if (node.left != null) nextLevel.add(node.left);
                    if (node.right != null) nextLevel.add(node.right);
                }
                level = nextLevel;
                result.add(levelRes);
            }
            return result;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.