Exemplo n.º 1
0
    def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
        if not root:
            return None

        root.left = self.removeLeafNodes(root.left, target)
        root.right = self.removeLeafNodes(root.right, target)
        if not root.left and not root.right and root.val == target:
            return None
        else:
            return root
Exemplo n.º 2
0
 def flatten(self, root: TreeNode) -> None:
     """
     Do not return anything, modify root in-place instead.
     """
     if not root:
         return None
     self.flatten(root.right)
     self.flatten(root.left)
     root.right = self.pre
     root.left = None
     self.pre = root
Exemplo n.º 3
0
 def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
     if not postorder:
         return None
     # 从后续遍历中获取根节点
     v = postorder[-1]
     # 从中序遍历中获取左右子树的分割点
     n = inorder.index(v)
     # 创建根节点
     root = TreeNode(v)
     # 根据n来构建二叉树进行分割递归
     root.left = self.buildTree(inorder[:n], postorder[:n])
     root.right = self.buildTree(inorder[n + 1:], postorder[n:-1])
     return root
Exemplo n.º 4
0
    def increasingBST(self, root: TreeNode) -> TreeNode:
        res = []

        def helper(root: TreeNode) -> List[int]:
            if not root:
                return
            helper(root.left)
            res.append(root.val)
            helper(root.right)
            return res

        helper(root)
        current = TreeNode(res[0])
        root = current
        for index, value in enumerate(res):
            if index + 1 >= len(res):
                break
            current.right = TreeNode(res[index + 1])
            current = current.right

        return root