Simple Java 1ms solution using Recursion


  • 0
    S
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> traverse = new ArrayList<>();
            helper(traverse, root, 0);
            return traverse;
        }
    
        public void helper(List<List<Integer>> traverse, TreeNode node, int counter) {
            if(node!=null){
                if (counter>=traverse.size()){
                    traverse.add(counter, new ArrayList<Integer>());
                }
                traverse.get(counter).add(node.val);
                counter++;
                helper(traverse, node.left, counter);
                helper(traverse, node.right, counter);
            }
        }
    }
    

Log in to reply
 

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