python中的二叉树
在刷算法题中,二叉树是常见的题型,掌握二叉树的基本语法和常见操作是非常重要的。以下是一些在Python中常用的二叉树语法及操作,特别是刷算法题时用到的。
1. 二叉树的定义:
首先定义二叉树的节点结构。每个节点通常有三个属性:val(节点的值),left(左子节点),right(右子节点)。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
2. 二叉树的常见操作:
tip: 先序,中序,后序遍历可以看作是深度优先搜索,层序遍历看作是广度优先搜索
1) 先序遍历 (Preorder Traversal):
先序遍历是指根节点 -> 左子树 -> 右子树。递归实现和迭代实现都很常见。
递归实现:
def preorderTraversal(root):
if root:
print(root.val) # 访问根节点
preorderTraversal(root.left) # 访问左子树
preorderTraversal(root.right) # 访问右子树
迭代实现(使用栈):
def preorderTraversal(root):
if not root:
return []
stack, result = [root], []
while stack:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right) # 先右后左,保证左子树先访问
if node.left:
stack.append(node.left)
return result
2) 中序遍历 (Inorder Traversal):
中序遍历是指左子树 -> 根节点 -> 右子树。常用于二叉搜索树的操作。
递归实现:
def inorderTraversal(root):
if root:
inorderTraversal(root.left) # 访问左子树
print(root.val) # 访问根节点
inorderTraversal(root.right) # 访问右子树
迭代实现(使用栈):
def inorderTraversal(root):
stack, result = [], []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
result.append(root.val)
root = root.right
return result
3) 后序遍历 (Postorder Traversal):
后序遍历是指左子树 -> 右子树 -> 根节点。
递归实现:
def postorderTraversal(root):
if root:
postorderTraversal(root.left) # 访问左子树
postorderTraversal(root.right) # 访问右子树
print(root.val) # 访问根节点
迭代实现(使用栈):
def postorderTraversal(root):
stack, result = [], []
last_visited = None
while stack or root:
if root:
stack.append(root)
root = root.left
else:
peek_node = stack[-1]
if peek_node.right and last_visited != peek_node.right:
root = peek_node.right
else:
result.append(peek_node.val)
last_visited = stack.pop()
return result
4) 层次遍历 (Level Order Traversal):
层次遍历是指按层访问节点,从上到下,从左到右。
from collections import deque
def levelOrder(root):
if not root:
return []
queue, result = deque([root]), []
while queue:
level_size = len(queue)
level_values = []
for _ in range(level_size):
node = queue.popleft()
level_values.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_values)
return result
3. 二叉树的构建:
在许多刷题过程中,你可能会遇到根据输入数组构建二叉树的情况。常见的构建方法是使用队列进行层序遍历。
根据数组构建二叉树:
from collections import deque
def buildTree(arr):
if not arr:
return None
root = TreeNode(arr[0])
queue = deque([root])
i = 1
while queue and i < len(arr):
node = queue.popleft()
if arr[i] is not None:
node.left = TreeNode(arr[i])
queue.append(node.left)
i += 1
if i < len(arr) and arr[i] is not None:
node.right = TreeNode(arr[i])
queue.append(node.right)
i += 1
return root
4. 常见二叉树问题:
1) 最大深度 (Maximum Depth of Binary Tree):
def maxDepth(root):
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return max(left_depth, right_depth) + 1
2) 路径总和 (Path Sum):
def hasPathSum(root, target):
if not root:
return False
if not root.left and not root.right:
return root.val == target
return hasPathSum(root.left, target - root.val) or hasPathSum(root.right, target - root.val)
3) 对称二叉树 (Symmetric Tree):
def isSymmetric(root):
def isMirror(t1, t2):
if not t1 and not t2:
return True
if not t1 or not t2:
return False
return (t1.val == t2.val) and isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)
if not root:
return True
return isMirror(root.left, root.right)
4) 二叉树的最小深度 (Minimum Depth of Binary Tree):
def minDepth(root):
if not root:
return 0
if not root.left:
return minDepth(root.right) + 1
if not root.right:
return minDepth(root.left) + 1
return min(minDepth(root.left), minDepth(root.right)) + 1
5. 总结:
- 递归遍历: 适用于树的遍历、查找等操作。
- 迭代遍历: 通常使用栈来实现递归遍历。
- 层次遍历: 使用队列进行广度优先搜索(BFS)。
- 树的构建: 可以使用层序遍历构建树,通常会用队列来帮助。
- 二叉树的基本操作: 最大深度、路径求和、对称性判断等是常见的算法题。
在刷算法题时,理解二叉树的基本操作和常见的模式非常重要。

浙公网安备 33010602011771号