Python, Straightforward with Explanation

  • 0

    Let's perform this recursively.

    • When d is 1, depending on the direction we went previously (default is left), we need to make a node with value v and put the rest of the tree as either the left or right child.

    • Otherwise, we'll recursively perform our operation on the children of our node, with the depth decremented by 1.

    def addOneRow(self, root, v, d, direction = 'left'):
        if d == 1:
            ans = TreeNode(v)
            setattr(ans, direction, root)
            return ans
        elif root:
            root.left = self.addOneRow(root.left, v, d-1, 'left')
            root.right = self.addOneRow(root.right, v, d-1, 'right')
            return root

Log in to reply

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