Python simple DFS

  • 0

    Add new left & right node at depth "d-1".

    class Solution(object):
        def addOneRow(self, root, v, d):
            dummy = TreeNode(0)
            dummy.left = root
            self.dfs(dummy, 0, v, d)
            return dummy.left
        def dfs(self, root, curr, v, d):
            if not root:
            if curr == d - 1:
                lnode, rnode = TreeNode(v), TreeNode(v)
                root.left, lnode.left = lnode, root.left
                root.right, rnode.right = rnode, root.right
            self.dfs(root.left, curr+1, v, d)
            self.dfs(root.right, curr+1, v, d)

Log in to reply

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