Simple python solution


  • 0
    A

    class Solution(object):
    def addOneRow(self, root, v, d):

    """
    :type root: TreeNode
    :type v: int
    :type d: int
    :rtype: TreeNode
    """

        if root is None:
            if d == 1:
                root = TreeNode(v)
            return root
    
        if d == 1:
            new_node= TreeNode(v)
            new_node.left = root
            return new_node
            
        if d == 2:
            l, r = root.left, root.right
            new_l, new_r = TreeNode(v), TreeNode(v)
            new_l.left, new_r.right = l, r
            root.left, root.right = new_l, new_r
            return root
            
        left = self.addOneRow(root.left, v, d-1)
        right = self.addOneRow(root.right, v, d-1)
        
        root.left, root.right = left, right
        
        return root

Log in to reply
 

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