Example #1
0
 def buildChildTree(pre_l: int, pre_r: int, ino_l: int, ino_r: int) -> TreeNode or None:
     root = None
     if pre_l <= pre_r:
         root = TreeNode(preorder[pre_l])
         index = dic[preorder[pre_l]]
         size_l = index - ino_l
         root.left = buildChildTree(pre_l + 1, pre_l + size_l, ino_l, ino_l + size_l - 1)
         root.right = buildChildTree(pre_l + 1 + size_l, pre_r, ino_l + size_l + 1, ino_r)
     return root
Example #2
0
    def recurseMerge(node1: TreeNode, node2: TreeNode) -> None or TreeNode:
        if not node1:
            return node2
        if not node2:
            return node1

        result = TreeNode(node1.val + node2.val)
        result.left = recurseMerge(node1.left, node2.left)
        result.right = recurseMerge(node1.right, node2.right)
        return result
Example #3
0
 def constructChild(the_num: List[int]) -> TreeNode or None:
     if the_num:
         index = 0
         for indexes in range(0, len(the_num)):
             if the_num[indexes] > the_num[index]:
                 index = indexes
         result = TreeNode(the_num[index])
         result.left = constructChild(the_num[:index])
         result.right = constructChild(the_num[index + 1:])
         return result
 def constructChild(left_index: int, right_index: int) -> TreeNode or None:
     if left_index != right_index:
         index = cur = left_index
         while cur < right_index:
             if nums[cur] > nums[index]:
                 index = cur
             cur += 1
         result = TreeNode(nums[index])
         result.left = constructChild(left_index, index)
         result.right = constructChild(index + 1, right_index)
         return result
Example #5
0
 def recursion(pre: List[int], ino: List[int]) -> TreeNode or None:
     root = None
     if pre:
         root = TreeNode(pre[0])
         index = 0
         #  每次都线性查找
         while index <= len(ino) - 1:
             if ino[index] != pre[0]:
                 index += 1
             else:
                 break
         root.left = recursion(pre[1:1 + index], ino[:index])
         root.right = recursion(pre[1 + index:], ino[index + 1:])
     return root
Example #6
0
 def recurseMerge(nodes: List[TreeNode]) -> None or TreeNode:
     if not nodes[0] and not nodes[1]:
         return
     result = TreeNode()
     left = []
     right = []
     if nodes[0]:
         result.val += nodes[0].val
         left.append(nodes[0].left)
         right.append(nodes[0].right)
     else:
         left.append(None)
         right.append(None)
     if nodes[1]:
         result.val += nodes[1].val
         left.append(nodes[1].left)
         right.append(nodes[1].right)
     else:
         left.append(None)
         right.append(None)
     result.left = recurseMerge(left)
     result.right = recurseMerge(right)
     return result