Simple JavaScript O(2^d) solution using DFS, no helper


  • 0
    var addOneRow = function(root, v, d, level = 1) {
        if (!root) return;
        if (d === 1) {
            const newRoot = new TreeNode(v);
            newRoot.left = root;
            return newRoot;
        } else if (d === level + 1) {
            const oldLeft = root.left;
            const oldRight = root.right;
            root.left = new TreeNode(v);
            root.right = new TreeNode(v);
            root.left.left = oldLeft;
            root.right.right = oldRight;
        } else {
            addOneRow(root.left, v, d, level + 1);
            addOneRow(root.right, v, d, level + 1);
        }
        return root;
    };
    

Log in to reply
 

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