def insert(self, v: int) -> int: n = len(self.memo) p_node = self.memo[(n - 1) // 2] if n % 2 == 1: # adds left child p_node.left = TreeNode(v) self.memo.append(p_node.left) else: # adds right child p_node.right = TreeNode(v) self.memo.append(p_node.right) return p_node.val
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 deserialize(self, data: str) -> TreeNode: if not data or data == '[]': return None data = data[1:-1].split(',') root = TreeNode(int(data[0])) idx, queue = 0, [root] while queue: cur = queue.pop(0) if idx * 2 + 1 < len(data) and data[idx * 2 + 1] != 'null': cur.left = TreeNode(int(data[idx * 2 + 1])) queue.append(cur.left) if idx * 2 + 2 < len(data) and data[idx * 2 + 2] != 'null': cur.right = TreeNode(int(data[idx * 2 + 2])) queue.append(cur.right) idx += 1 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
def insert(tree: TreeNode, data): if tree is None: return TreeNode(data) p = tree if data > p.val: if p.right is None: p.right = TreeNode(data) return tree else: return BinarySearchTree.insert(p.right, data) else: # data <= p.val if p.left is None: p.left = TreeNode(data) return tree else: return BinarySearchTree.insert(p.left, data)
def insert_iterative(tree: TreeNode, data): if tree is None: return TreeNode(data) p = tree while p is not None: if data > p.val: if p.right is None: p.right = TreeNode(data) return tree else: p = p.right else: # data <= p.val if p.left is None: p.left = TreeNode(data) return tree else: p = p.left
def convert_bst(self, root: TreeNode) -> TreeNode: ''' 二分查找树 Args: root: 根节点 Returns: 节点的值 ''' global total_sum if not root: self.convert_bst(root.right) total_sum += root.val root.val = total_sum self.convert_bst(root.left) return root
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))
root: 根节点 ''' if root.left: self.helper(result, root.left) if root.right: self.helper(result, root.right) result.append(root.val) def post_order_traversal(self, root: TreeNode) -> List[int]: ''' 后序遍历 Args: res: 链表 root: 根节点 ''' result = [] if not root: return result self.helper(result, root) return result if __name__ == '__main__': arr = [1, 2, 3, 4, 5] tree_node = TreeNode() tree = tree_node.create_binary_tree_array(arr) solution = Solution() result = solution.post_order_traversal(tree) print(result) assert result[len(result) - 1] == 1
Returns: 布尔值 ''' queue = [] queue.append(root) queue.append(root) while queue: r1 = queue.pop() r2 = queue.pop() if not r1 and not r2: continue if not r1 or not r2: return False if r1.val != r2.val: return False queue.append(r1.left) queue.append(r2.right) queue.append(r1.right) queue.append(r2.left) return True if __name__ == '__main__': arr1 = [1, 2, 2] tree_node = TreeNode() root = tree_node.create_binary_tree_array(arr1) solution = Solution() result = solution.is_symmetric2(root) print(result) assert result == True
def build(self, array, p, q): nodes = {} for v in array: if v != None: nodes[v] = TreeNode(v) return nodes, nodes[p], nodes[q]
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))
''' if t1 == None: return t2 if t2 == None: return t1 stack = [] stack.append((t1, t2)) while stack: t = stack.pop() if t[0] == None or t[1] == None: continue t[0].val += t[1].val if t[0].left == None: t[0].left = t[1].left else: stack.append((t[0].left, t[1].left)) if t[0].right == None: t[0].right = t[1].right else: stack.append((t[0].right, t[1].right)) return t1 if __name__ == '__main__': tree_node = TreeNode() t1 = tree_node.create_binary_tree_array([1, 2, 3], 0) t2 = tree_node.create_binary_tree_array([1, 2, 3], 0) t = merge_trees2(t1, t2) t_arr = per_order_traversal(t) print(t_arr)
root: 节点root p: 节点p q: 节点q Returns: 最小公共祖先 ''' if not root: return root if not p or not q: return root left = lowest_common_ancestor(root.left, p, q) right = lowest_common_ancestor(root.right, p, q) if not left and not right: return None if left and right: return root if not left: return right else: return left if __name__ == '__main__': nums = [3, 5, 1, 6, 2, 0, 8, None, None, 7, 4] tree_node = TreeNode() p = TreeNode(5) q = TreeNode(1) root = tree_node.create_binary_tree_array(nums) result = lowest_common_ancestor(root, p, q) print(result)
@staticmethod def height(root: TreeNode): if root is None: return 0 else: # compute the height of each subtree l_height = BinaryTreeTraversal.height(root.left) r_height = BinaryTreeTraversal.height(root.right) # return the larger one return max(l_height, r_height) + 1 if __name__ == '__main__': # construct a binary tree d = TreeNode('d') e = TreeNode('e') f = TreeNode('f') g = TreeNode('g') b = TreeNode('b', d, e) c = TreeNode('c', f, g) a = TreeNode('a', b, c) # traverse the binary via different approaches print('pre-order:', end='\t\t') BinaryTreeTraversal.pre_order(a) print('\nin-order:', end='\t\t') BinaryTreeTraversal.in_order(a)
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)
def invert_tree2(self, root: TreeNode) -> TreeNode: ''' 翻转二叉树 Args: root: 根节点 Returns: TreeNode ''' if root == None: return None node_list = [] node_list.append(root) while len(node_list) > 0: cur = node_list.pop() if cur.left: node_list.append(cur.left) if cur.right: node_list.append(cur.right) temp = cur.right cur.right = cur.left cur.left = temp return root if __name__ == '__main__': arr = [4, 2, 7, 1, 3, 6, 9] root = TreeNode.create_binary_tree_array(arr) solution = Solution() result = solution.invert_tree(root) assert 4 == result.val
elif p.right is not None: child = p.right if pp is None: tree = child elif pp.left == p: pp.left = child else: pp.right = child return tree if __name__ == '__main__': # construct a binary tree m_19 = TreeNode(19) n_27 = TreeNode(27) o_55 = TreeNode(55) h_15 = TreeNode(15) i_17 = TreeNode(17) j_25 = TreeNode(25, m_19, n_27) k_51 = TreeNode(51, right=o_55) l_66 = TreeNode(66) d_13 = TreeNode(13, right=h_15) e_18 = TreeNode(18, i_17, j_25) f_34 = TreeNode(34) g_58 = TreeNode(58, k_51, l_66) b_16 = TreeNode(16, d_13, e_18)
def is_valid_BST_2(self, root: TreeNode) -> bool: ''' 中序遍历二叉树判断是不是BST树 Args: root: 根节点 Returns: 布尔值 ''' pre = -sys.maxsize stack = [] while not root or len(stack) < 1: while not root.left: stack.append(root.left) root = root.left # 栈退出一个元素 root = stack.pop() if root.val <= pre: return False pre = root.val root = root.right return True if __name__ == '__main__': nums = [2, 1, 3] tree = TreeNode() root = tree.create_binary_tree_array(nums) solution = Solution() result = solution.is_valid_BST(root) assert result == True