def mirrorTree(self, root: TreeNode) -> TreeNode: #递归交换左右节点 if not root: return root root.left, root.right = root.right, root.left if root.left: self.mirrorTree(root.left) if root.right: self.mirrorTree(root.right) return root
def buildTree_recur(preorder: List[int], inorder: List[int]) -> TreeNode: if (len(preorder) <= 0): return None #先序中的第一个元素是根节点 rootVal = preorder[0] idx = inorder.index(rootVal) # 构建左右子树 root = TreeNode(rootVal) root.left = buildTree_recur(preorder[1:idx + 1], inorder[0:idx]) #0省略 root.right = buildTree_recur(preorder[idx + 1:len(preorder)], inorder[idx + 1:len(inorder)]) #len省略 return root
def sortedListToBST(head: ListNode) -> TreeNode: if head is None: return None if head.next is None: return TreeNode(head.val) fast = slow = prev = head while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next # 根据中间节点一分为二 prev.next = None head2 = slow.next node = TreeNode(slow.val) node.left = sortedListToBST(head) node.right = sortedListToBST(head2) return node
def build(preorder_left, preorder_right, inorder_left, inorder_right) -> TreeNode: if (preorder_left > preorder_right): return None # 前序遍历中的第一个节点就是根节点 preorder_root = preorder_left # 在中序遍历中定位根节点 inorder_root = index[preorder[preorder_root]] # 先把根节点建立出来 root = TreeNode(preorder[preorder_root]) # 得到左子树中的节点数目 size_left_subtree = inorder_root - inorder_left # 递归地构造左子树,并连接到根节点 # 先序遍历中「从 左边界+1 开始的 size_left_subtree」个元素就对应了中序遍历中「从 左边界 开始到 根节点定位-1」的元素 root.left = build(preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1) # 递归地构造右子树,并连接到根节点 # 先序遍历中「从 左边界+1+左子树节点数目 开始到 右边界」的元素就对应了中序遍历中「从 根节点定位+1 到 右边界」的元素 root.right = build(preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right) return root