def buildTree_withList(self, pre: List[int], inorder: List[int]) -> TreeNode: if not pre: return root=TreeNode(pre[0]) ind=inorder.index(pre[0]) root.left=self.buildTree(pre[1:ind+1],inorder[:ind]) root.right=self.buildTree(pre[ind+1:],inorder[ind+1:]) return root
def flatten_recur(self, root: TreeNode) -> None: # 递归版本,先初始化左子树,然后找到左子树链表的尾节点,然后进行拼接 if not root: return self.flatten(root.right) right = root.right self.flatten(root.left) root.right, root.left = root.left, None while root.right: root = root.right root.right = right
def helper(start,end): if start>end:return nonlocal post_idx root_val=postorder[post_idx] root=TreeNode(root_val) post_idx-=1 idx=idx_map[root_val] root.right=helper(idx+1,end) root.left=helper(start,idx-1) return root
def generateTrees(start, end): if end == start + 1: return [TreeNode(end)] elif end == start: return [None] res = [] for i in range(start, end): left = generateTrees(start, i) right = generateTrees(i + 1, end) for l in left: for r in right: curNode = TreeNode(i + 1) curNode.left = l curNode.right = r res.append(curNode) return res
def convert(l, r): nonlocal head if l > r: return None mid = (l + r) // 2 # 中序遍历左子树 left = convert(l, mid - 1) # 构造左子树之后构造当前节点 node = TreeNode(head.val) node.left = left head = head.next node.right = convert(mid + 1, r) return node
def helper(in_left=0, in_right=len(inorder)): if in_left == in_right: return None # pick up pre_idx element as a root nonlocal pre_idx root_val = preorder[pre_idx] root = TreeNode(root_val) # root splits inorder list # into left and right subtrees index = idx_map[root_val] # recursion pre_idx += 1 # build left subtree root.left = helper(in_left, index) # build right subtree root.right = helper(index + 1, in_right) return root
def recoverTree(self, root: TreeNode) -> None: """ 二叉搜索树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。 想到中序遍历,然后把违反顺序的两个节点交换,第一个错误节点比后面的节点大,第二个错误节点比前面的节点小,两个节点可能紧挨,比前面节点小的节点可能有两个 该算法可以写成非递归的 # 这个题还有一种思路就是,在遍历的时候,边遍历,边对树进行线索化,然后只需要记录一个节点,就可以完成遍历,但是会修改树 """ self.disorder1=None self.disorder2=None self.pre=TreeNode(float('-inf')) try:self.recover(root) except:pass self.disorder1.val,self.disorder2.val=self.disorder2.val,self.disorder1.val
maxSum = max(maxSum, stack[-1][1]) root = root.left else: root = stack[-1][0].right if not root: pre, _ = stack.pop() while len(stack) > 1 and stack[-1][0].right == pre: pre, _ = stack.pop() return maxSum def maxPathSum(self, root: TreeNode) -> int: maxPath = -float('inf') def maxPathCore(root: TreeNode) -> int: if not root: return 0 nonlocal maxPath left = maxPathCore(root.left) right = maxPathCore(root.right) maxPath = max(maxPath, left + right + root.val) return max(left + root.val, right + root.val, 0) maxPathCore(root) return maxPath root = TreeNode.createTree([-10]) print(Solution124().maxPathSum(root))
start, end = end, end * 2 + 1 p = p.right def isExists(mid): p = root stack = [] while mid > 1: stack.append(mid & 1) mid >>= 1 for i in reversed(stack): if i: p = p.right else: p = p.left return not p is None while start < end - 1: mid = (start + end) >> 1 if isExists(mid): start = mid else: end = mid return start n = random.randint(0, 100) print(n) root = TreeNode.createTree(list(range(1, n + 1))) print(Solution().countNodes(root))
def connect(self, root: 'Node') -> 'Node': node = root while node: leftmost = None pre = None while node: if leftmost: if node.left: pre.next = node.left if pre != node.left else None pre = node.left if node.right: pre.next = node.right if pre != node.right else None pre = node.right else: if node.left: leftmost = node.left pre = leftmost continue if node.right: leftmost = node.right pre = leftmost node = node.next node = leftmost return root null = '$' root = TreeNode.createTree([1, 2]) root.printTree() root = Solution().connect(root) root.printTree()
res.append(cur.val) if cur.left: stack.append(cur.left) if cur.right: stack.append(cur.right) return res[::-1] def postorderTraversal_flag(self, root: TreeNode) -> List[int]: # 通过标记记录是否访问完孩子节点 res = [] stack = [[root, 0]] if root else [] while stack: if not stack[-1][1]: cur = stack[-1] if cur[0].right: stack.append([cur[0].right, 0]) if cur[0].left: stack.append([cur[0].left, 0]) cur[1] = 1 else: cur = stack.pop() res.append(cur[0].val) return res null = '$' root = TreeNode.deserialize([1, null, 2, 3]) for i in Solution().postorderTraversal(root): print(i, end=' ')
root.right, root.left = root.left, None while root.right: root = root.right root.right = right def flatten(self, root: TreeNode) -> None: # 保存一个pre的元素,只需要对这个元素进行修改即可,是以上两个版本的改进 if not root: return self.pre = root def visit(root): self.pre.right=root self.pre.left=None self.pre=root right=root.right if root.right else None if root.left: visit(root.left) if right: visit(right) right = root.right if root.right else None if root.left: visit(root.left) if right: visit(right) null='$' root=TreeNode.createTree([1,2,5,3,4,null,6]) Solution().flatten(root) root.printTree()
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': ppath, qpath = None, None def dfs(root, path): nonlocal ppath, qpath if not root or (ppath and qpath): return path.append(root) if root.val == q.val: qpath = path.copy() if root.val == p.val: ppath = path.copy() dfs(root.left, path) dfs(root.right, path) path.pop() dfs(root, []) res = root for i, j in zip(qpath, ppath): if i == j: res = i return res null = '$' root = TreeNode.createTree([3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]) root.printTree() print(Solution().lowestCommonAncestor(root, TreeNode(5), TreeNode(4)))