DEV Community

Karleb
Karleb

Posted on

#623. Add One Row to Tree

https://leetcode.com/problems/add-one-row-to-tree/description/?envType=daily-question&envId=2024-04-16



function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}


var addOneRow = function(root, val, depth) {
    if (depth === 1) {
        const newRoot = new TreeNode(val)
        newRoot.left = root
        return newRoot
    }

    function traverse(node, d) {
        if (!node) return

        if (d === depth - 1) {
            const left = node.left
            const right = node.right 

            node.left = new TreeNode(val)
            node.right = new TreeNode(val)

            node.left.left = left
            node.right.right = right 
        } else {
            traverse(node.left, d + 1)
            traverse(node.right, d + 1)
        }
    }



    traverse(root, 1)
    return root

};



```




Enter fullscreen mode Exit fullscreen mode

Top comments (0)