def invert_tree(self, root: TreeNode) -> TreeNode: ''' 翻转二叉树 Args: root: 根节点 Returns: TreeNode ''' if root == None: return None left = self.invert_tree(root.left) right = self.invert_tree(root.right) root.left = right root.right = left return root
def flatten_for_list(self, root: TreeNode, current_node) -> TreeNode: ''' 循环递归树 Args: root: 根节点 current_node: 当前节点 Returns: root ''' if not root: return current_node current_node = self.flatten_for_list(root.right, current_node) current_node = self.flatten_for_list(root.left, current_node) root.left = None root.right = current_node return root
def merge_trees(t1: TreeNode, t2: TreeNode) -> TreeNode: ''' 合并两棵二叉树 Args: t1: 二叉树t1 t2: 二叉树t2 Returns: 合并后的二叉树 ''' if t1 == None: return t2 if t2 == None: return t1 t1.val += t2.val t1.left = merge_trees(t1.left, t2.left) t1.right = merge_trees(t1.right, t2.right) return t1
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. """ from tree.tree_node import TreeNode def invert_binary_tree(root: TreeNode): if not root: return None stack = [root] # stack存放还没有做对换的节点 while stack: node = stack.pop() if not node: continue node.left, node.right = node.right, node.left stack.append(node.left) stack.append(node.right) return root t = TreeNode(4) t.left = TreeNode(2) t.left.left = TreeNode(1) t.left.right = TreeNode(3) t.right = TreeNode(7) t.right.left = TreeNode(6) t.right.right = TreeNode(9) print(invert_binary_tree(t))
def max_depth(root: TreeNode): if not root: return 0 q = [root] step = 1 all_step = [] while q: n = len(q) for _ in range(n): node = q.pop(0) if not node: continue if not node.left and not node.right: all_step.append(step) q.append(node.left) q.append(node.right) step += 1 return max(all_step) t = TreeNode(3) t.left = TreeNode(9) t.right = TreeNode(20) t.right.left = TreeNode(15) t.right.right = TreeNode(7) print(min_depth(t)) print(max_depth(t))
self.in_order(root.left) if self.pre and self.pre.val > root.val: if not self.first: self.first = self.pre self.second = root self.pre = root self.in_order(root.right) def recover_tree(self, root: TreeNode): self.in_order(root) self.first.val, self.second.val = self.second.val, self.first.val r = TreeNode(3) r.left = TreeNode(1) r.right = TreeNode(4) r.right.left = TreeNode(2) recover = RecoverTree() recover.recover_tree(r)