1ms easy java solution using recursive preorder traversal beat 88%


  • 1
    X
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<List<Integer>>();
        preTraversal(levels, root, 0);
        return levels;
    }
    
    private void preTraversal(List<List<Integer>> levels, TreeNode root, int n){
        if (root == null){
            return;
        } else {
            if (levels.size() == n){
                levels.add(new ArrayList<Integer>());
            }
            levels.get(n).add(root.val);
            preTraversal(levels, root.left, n+1);
            preTraversal(levels, root.right, n+1);
        }
    }

Log in to reply
 

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