tree = s.buildTree(preorder, inorder) preOrderTraverse(tree) print() inOrderTraverse(tree) print() postOrderTraverse(tree) print() # 后序 创建 tree = s.buildTree_post(postorder, inorder) preOrderTraverse(tree) print() inOrderTraverse(tree) print() postOrderTraverse(tree) print() if __name__ == '__main__': # 有 先序/后序 + 中序 重新创建树 # rebuild_tree() tree = build_tree_from_arr(arr=[3, 9, 20, None, None, 15, 7]) preOrderTraverse(tree) print() inOrderTraverse(tree) print() postOrderTraverse(tree) print()
tar -= root.val # 更新寻找的路径目标值 if tar == 0 and not root.left and not root.right: # 题目限制了是叶节点 # if tar == 0: # 假设可以不到叶节点,且节点值>0, pop() 剪枝 res.append(path[:]) # copy 一份 path,因为后面 path 还要用于 pop 寻找其他解 recur(root.left, tar) recur(root.right, tar) path.pop() # 包含当前 root 的 path 研究完了 recur(root, sum) return res if __name__ == '__main__': from base.tree import build_tree_from_arr, layerTraverse s = Solution() # tree = build_tree_from_arr([1, 2, 3, 4, 5]) # print(s.pathSum_slow(tree, 4)) # print(s.pathSum(tree, 4)) tree = build_tree_from_arr( [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, None, 5, 1]) # print(s.pathSum_slow(tree, 22)) print(s.pathSum(tree, 22)) # layerTraverse(tree)
self.val = x self.left = None self.right = None class Solution: # 平衡二叉树,任意节点 左右子树深度差 <= 1 # 推出:树的深度 = 左子树的深度 与 右子树的深度 中的 最大值 +1 def isBalanced(self, root: TreeNode) -> bool: def recur(root: TreeNode): if not root: return 0 left = recur(root.left) if left == -1: # 使用 -1 剪枝,提前返回结果 return -1 right = recur(root.right) if right == -1: return -1 # 满足平衡二叉树,则返回树的深度 return max(left, right) + 1 if abs(left - right) <= 1 else -1 return recur(root) != -1 from base.tree import build_tree_from_arr # tree = build_tree_from_arr([3, 9, 20, None, None, 15, 7]) tree = build_tree_from_arr([1, 2, 2, 3, 3, None, None, 4, 4]) s = Solution() print(s.isBalanced(tree))
self.left = None self.right = None class Solution: # 二叉搜索树的第 k 大节点 def kthLargest(self, root: TreeNode, k: int) -> int: vals = [] def inorder(node: TreeNode): if not node: # 加了这个 提速很多 return if node.left: # 先添加 right, 再 left, 可以得到降序序列 inorder(node.left) vals.append(node.val) if node.right: inorder(node.right) inorder(root) return vals[len(vals) - k] from base.tree import build_tree_from_arr, inOrderTraverse s = Solution() # tree = build_tree_from_arr([3, 1, 4, None, 2]) # print(s.kthLargest(tree, 1)) tree = build_tree_from_arr([5, 3, 6, 2, 4, None, None, 1]) # 保证完全二叉树即可 print(s.kthLargest(tree, 3))