二叉树基本概念
二叉树是一种树形数据结构,每个节点最多有两个子节点(左子节点和右子节点)。常见类型包括:
- 满二叉树:所有非叶子节点都有两个子节点,且所有叶子节点在同一层。
- 完全二叉树:除最后一层外,其他层节点数达到最大,最后一层节点从左向右填充。
- 二叉搜索树(BST):左子树所有节点值小于根节点,右子树所有节点值大于根节点。
Python实现二叉树节点
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
常见考试要点
二叉树的遍历(递归与非递归)
-
前序遍历 :根→左→右
pythondef preorder(root): if not root: return [] return [root.val] + preorder(root.left) + preorder(root.right) -
中序遍历 :左→根→右(BST中结果为有序序列)
pythondef inorder(root): if not root: return [] return inorder(root.left) + [root.val] + inorder(root.right) -
后序遍历 :左→右→根
pythondef postorder(root): if not root: return [] return postorder(root.left) + postorder(root.right) + [root.val]
二叉树的高度与深度
python
def max_depth(root):
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
判断平衡二叉树
平衡二叉树定义为左右子树高度差不超过1。
python
def is_balanced(root):
def check(node):
if not node:
return 0
left = check(node.left)
right = check(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
二叉搜索树操作
-
验证BST :利用中序遍历是否有序。
pythondef is_valid_bst(root, min_val=float('-inf'), max_val=float('inf')): if not root: return True if root.val <= min_val or root.val >= max_val: return False return (is_valid_bst(root.left, min_val, root.val) and is_valid_bst(root.right, root.val, max_val)) -
插入节点 :递归或迭代实现。
pythondef insert_into_bst(root, val): if not root: return TreeNode(val) if val < root.val: root.left = insert_into_bst(root.left, val) else: root.right = insert_into_bst(root.right, val) return root
二叉树序列化与反序列化
python
def serialize(root):
if not root:
return "None"
return f"{root.val},{serialize(root.left)},{serialize(root.right)}"
def deserialize(data):
def helper(nodes):
val = next(nodes)
if val == "None":
return None
node = TreeNode(int(val))
node.left = helper(nodes)
node.right = helper(nodes)
return node
nodes = iter(data.split(','))
return helper(nodes)
高频考题示例
- 求二叉树的最大路径和(LeetCode 124)。
- 最近公共祖先(LCA)问题(LeetCode 236)。
- 层序遍历(BFS)及其变种(如锯齿形遍历)。
- 根据前序和中序遍历序列重建二叉树(LeetCode 105)。
掌握以上内容可覆盖多数二叉树相关考试题目,建议结合递归和迭代两种方法练习。