二叉树算法实战教程

📅 2026/7/2 2:46:08
二叉树算法实战教程
二叉树算法实战教程二叉树作为数据结构中的核心概念在算法领域扮演着至关重要的角色。无论是面试准备还是实际开发掌握二叉树算法都是程序员必备的技能。本文将带你深入理解二叉树并通过实战案例掌握关键算法。二叉树基础回顾二叉树是每个节点最多有两个子节点的树结构通常称为左子节点和右子节点。二叉树有多种特殊形式满二叉树、完全二叉树、二叉搜索树BST、平衡二叉树如AVL树等。其中二叉搜索树最为常见它满足左子树所有节点值小于根节点右子树所有节点值大于根节点的性质。二叉树遍历实战遍历是二叉树算法的基础主要有四种方式前序遍历、中序遍历、后序遍历和层次遍历。递归实现示例pythonclass TreeNode:def __init__(self, val0, leftNone, rightNone):self.val valself.left leftself.right right前序遍历根-左-右def preorder_traversal(root):if not root:return []return [root.val] preorder_traversal(root.left) preorder_traversal(root.right)中序遍历左-根-右对BST会得到有序序列def inorder_traversal(root):if not root:return []return inorder_traversal(root.left) [root.val] inorder_traversal(root.right)后序遍历左-右-根def postorder_traversal(root):if not root:return []return postorder_traversal(root.left) postorder_traversal(root.right) [root.val]迭代实现示例前序遍历pythondef preorder_iterative(root):if not root:return []result []stack [root]while stack:node stack.pop()result.append(node.val)注意先右后左因为栈是LIFOif node.right:stack.append(node.right)if node.left:stack.append(node.left)return result二叉搜索树实战二叉搜索树BST因其高效的查找、插入和删除操作而广泛应用。BST查找实现pythondef search_bst(root, target):if not root or root.val target:return rootif target root.val:return search_bst(root.left, target)else:return search_bst(root.right, target)BST插入操作pythondef insert_bst(root, val):if not root:return TreeNode(val)if val root.val:root.left insert_bst(root.left, val)else:root.right insert_bst(root.right, val)return rootBST删除操作最复杂pythondef delete_bst(root, key):if not root:return Noneif key root.val:root.left delete_bst(root.left, key)elif key root.val:root.right delete_bst(root.right, key)else:找到要删除的节点if not root.left:return root.rightelif not root.right:return root.left有两个子节点找到右子树的最小节点temp find_min(root.right)root.val temp.valroot.right delete_bst(root.right, temp.val)return rootdef find_min(node):current nodewhile current.left:current current.leftreturn current二叉树深度与高度计算计算二叉树最大深度pythondef max_depth(root):if not root:return 0return max(max_depth(root.left), max_depth(root.right)) 1判断平衡二叉树pythondef is_balanced(root):def check(node):if not node:return 0, Trueleft_height, left_balanced check(node.left)right_height, right_balanced check(node.right)balanced left_balanced and right_balanced and abs(left_height - right_height) 1return max(left_height, right_height) 1, balancedreturn check(root)[1]路径与求和问题二叉树路径总和问题pythondef has_path_sum(root, target_sum):if not root:return Falseif not root.left and not root.right:return target_sum root.valremaining target_sum - root.valreturn has_path_sum(root.left, remaining) or has_path_sum(root.right, remaining)找出所有路径总和等于目标值的路径pythondef path_sum_all(root, target_sum):def dfs(node, current_sum, path, result):if not node:returncurrent_sum node.valpath.append(node.val)if not node.left and not node.right and current_sum target_sum:result.append(list(path))dfs(node.left, current_sum, path, result)dfs(node.right, current_sum, path, result)path.pop()result []dfs(root, 0, [], result)return result二叉树构建问题从前序与中序遍历序列构造二叉树pythondef build_tree(preorder, inorder):if not preorder or not inorder:return Noneroot_val preorder[0]root TreeNode(root_val)root_index inorder.index(root_val)root.left build_tree(preorder[1:1root_index], inorder[:root_index])root.right build_tree(preorder[1root_index:], inorder[root_index1:])return root从后序与中序遍历序列构造二叉树pythondef build_tree_post(inorder, postorder):if not inorder or not postorder:return Noneroot_val postorder[-1]root TreeNode(root_val)root_index inorder.index(root_val)root.left build_tree_post(inorder[:root_index], postorder[:root_index])root.right build_tree_post(inorder[root_index1:], postorder[root_index:-1])return root最近公共祖先问题二叉树的最近公共祖先LCApythondef lowest_common_ancestor(root, p, q):if not root or root p or root q:return rootleft lowest_common_ancestor(root.left, p, q)right lowest_common_ancestor(root.right, p, q)if left and right:return rootreturn left if left else rightBST的最近公共祖先利用BST性质pythondef lowest_common_ancestor_bst(root, p, q):if p.val root.val and q.val root.val:return lowest_common_ancestor_bst(root.left, p, q)elif p.val root.val and q.val root.val:return lowest_common_ancestor_bst(root.right, p, q)else:return root二叉树序列化与反序列化二叉树的序列化与反序列化pythondef serialize(root):if not root:return nullreturn str(root.val) , serialize(root.left) , serialize(root.right)def deserialize(data):def helper(nodes):val next(nodes)if val null:return Nonenode TreeNode(int(val))node.left helper(nodes)node.right helper(nodes)return nodereturn helper(iter(data.split(,)))二叉树视图问题二叉树的右视图pythondef right_side_view(root):if not root:return []result []queue [root]while queue:level_size len(queue)for i in range(level_size):node queue.pop(0)if i level_size - 1:result.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)return result实战技巧总结1. 递归与迭代选择递归代码简洁但可能栈溢出迭代需要手动维护栈但更可控2. 空间复杂度优化某些问题可以用Morris遍历实现O(1)空间复杂度3. 模板化思考许多二叉树问题有固定解题模板如DFS、BFS模板4. 边界条件处理始终考虑空树、单节点树、左斜树、右斜树等边界情况5. 利用树的性质BST问题要充分利用其有序性质简化算法二叉树算法是算法学习的基石掌握这些核心算法不仅能帮助你在技术面试中脱颖而出更能提升解决实际问题的能力。建议通过LeetCode、Codeforces等平台多加练习从简单题开始逐步挑战难题将理论知识转化为实战能力。记住理解比死记硬背更重要掌握每个算法背后的思想才能灵活应对各种变体问题。