二叉树的基本概念
二叉树是一种常见的数据结构,由节点组成,每个节点最多有两个子节点,分别称为左子节点和右子节点。树的最顶层节点称为根节点,没有子节点的节点称为叶子节点。二叉树的高度是从根节点到最远叶子节点的最长路径上的节点数。
二叉树的遍历
二叉树的遍历是面试中的高频考点,主要包括前序遍历、中序遍历和后序遍历,以及层次遍历。
前序遍历:根节点 -> 左子树 -> 右子树
中序遍历:左子树 -> 根节点 -> 右子树
后序遍历:左子树 -> 右子树 -> 根节点
层次遍历:按层从左到右访问节点。
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 前序遍历(递归)
def preorder(root):
if not root:
return
print(root.val)
preorder(root.left)
preorder(root.right)
# 中序遍历(递归)
def inorder(root):
if not root:
return
inorder(root.left)
print(root.val)
inorder(root.right)
# 后序遍历(递归)
def postorder(root):
if not root:
return
postorder(root.left)
postorder(root.right)
print(root.val)
# 层次遍历(队列实现)
def level_order(root):
if not root:
return []
queue = [root]
res = []
while queue:
node = queue.pop(0)
res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
二叉树的最大深度
计算二叉树的最大深度是常见问题,通常通过递归或迭代的方式解决。
# 递归法
def max_depth(root):
if not root:
return 0
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
return max(left_depth, right_depth) + 1
# 迭代法(层次遍历)
def max_depth_iterative(root):
if not root:
return 0
queue = [root
907

被折叠的 条评论
为什么被折叠?



