Easy understand JavaScript Solution


  • 0
    S

    Traverse the whole tree, and every depth of the tree is an array

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[][]}
     */
    var levelOrder = function(root) {
        var res = [];
        helper(root, 0);
        return res;
        
        function helper(root, depth) {
            if(root == null) return;
            res[depth] = res[depth]  || [];
            res[depth].push(root.val);
            helper(root.left, depth+1);
            helper(root.right, depth+1);
        }
    };
    

Log in to reply
 

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