Exemplo n.º 1
0
    def buildTree(self, inorder: [int], postorder: [int]) -> TreeNode:
        """
        Solution:
        1. 如果 inorder 列表为空,返回 None
        2. 如果 inorder 长度为 1,直接返回
        3. 由 postorder[-1] 拿到根节点
        4. 找到根节点在 inorder[] 中的位置
        5. 根据 inorder 和 postorder 列表等长的特性
            1. 递归左子树
            2. 赌鬼右子树

        :param inorder:
        :param postorder:
        :return:
        """

        if not inorder:
            return None

        if len(inorder) == 1:
            return TreeNode(inorder[0])

        root = TreeNode(postorder[-1])
        sep = inorder.index(postorder[-1])
        if sep == 0:
            root.right = self.buildTree(inorder[1:], postorder[:-1])
        elif sep == len(inorder) - 1:
            root.left = self.buildTree(inorder[:-1], postorder[:-1])
        else:
            root.left = self.buildTree(inorder[:sep], postorder[:sep])
            root.right = self.buildTree(inorder[(sep + 1):], postorder[sep:-1])
        return root
Exemplo n.º 2
0
 def invertTree(self, root: TreeNode) -> TreeNode:
     if root:
         # 保存右节点的信息
         right = root.right
         # 右节点递归翻转
         root.right = self.invertTree(root.left)
         # 左节点递归翻转
         root.left = self.invertTree(right)
         return root
     else:
         return None
Exemplo n.º 3
0
def mergeTree2(t1: TreeNode, t2: TreeNode):
    if not t1 and not t2:
        return
    if not t1:
        t1 = t2
        return
    if not t2:
        return
    t1.val += t2.val
    if t1.left and t2.left:
        mergeTree2(t1.left, t2.left)
    elif t2.left:
        t1.left = t2.left

    if t1.right and t2.right:
        mergeTree2(t1.right, t2.right)
    elif t2.right:
        t1.right = t2.right