Recursive solution in 12 lines of codes


  • 0

    Use inorder to traverse the root recursively, record current depth and push current node.val to result of that level accordingly.

     /**
     * Complex: O(n)
     * Runtime: ms
     * Tests: 34 test cases passed
     * Rank: A
     */
    var levelOrder = function(root) {
        var result = [];
    
        var traverse = function(root, depth) {
            if (!root) return;
            if (!result[depth]) result[depth] = [];
            result[depth].push(root.val);
            traverse(root.left, depth + 1);
            traverse(root.right, depth + 1);
        };
    
        traverse(root, 0);
        return result;
    };

Log in to reply
 

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