def merge(t1, t2):
     if not t1: return t2
     if not t2: return t1
     root = TreeNode(t1.val + t2.val)
     root.left = merge(t1.left, t2.left)
     root.right = merge(t1.right, t2.right)
     return root
Example #2
0
def addOneRow(root, v, d):
    def attach(node, v, is_left=False):
        new_node = TreeNode(v)
        if is_left:
            new_node.left = node
        else:
            new_node.right = node
        return new_node

    def search(root, depth):
        if depth > d or root is None:
            return root
        if depth + 1 != d:
            search(root.left, depth + 1)
            search(root.right, depth + 1)
        else:
            root.left = attach(root.left, v, is_left=True)
            root.right = attach(root.right, v, is_left=False)
        return root

    if 1 == d:
        new_root = TreeNode(v)
        new_root.left = root
        return new_root
    else:
        return search(root, 1)
Example #3
0
 def attach(node, v, is_left=False):
     new_node = TreeNode(v)
     if is_left:
         new_node.left = node
     else:
         new_node.right = node
     return new_node
Example #4
0
    def build_tree(i, j):
        if j < i: return None

        max_val = nums[i]
        max_idx = i
        for idx in range(i + 1, j + 1):
            val = nums[idx]
            if val > max_val:
                max_idx = idx
                max_val = val

        root = TreeNode(max_val)
        root.left = build_tree(i, max_idx - 1)
        root.right = build_tree(max_idx + 1, j)
        return root