返回

二叉树的遍历之旅:前序、中序、后序大解密

后端

二叉树在计算机科学中扮演着举足轻重的角色,理解其遍历方法对于编程和算法至关重要。本文将深入探究二叉树的三个基本遍历方法:前序、中序和后序,为您提供一个清晰的模板化方法,无论是递归还是非递归,都能轻松掌握。

前序遍历

前序遍历按照以下顺序访问二叉树的节点:根节点、左子树、右子树。其递归模板如下:

def preorder_recursive(root):
  if root is None:
    return

  # 访问根节点
  print(root.val)

  # 前序遍历左子树
  preorder_recursive(root.left)

  # 前序遍历右子树
  preorder_recursive(root.right)

非递归模板则利用了栈的数据结构:

def preorder_iterative(root):
  if root is None:
    return

  stack = [root]

  while stack:
    # 访问栈顶元素(根节点)
    node = stack.pop()
    print(node.val)

    # 将右子树压入栈中
    if node.right:
      stack.append(node.right)

    # 将左子树压入栈中
    if node.left:
      stack.append(node.left)

中序遍历

中序遍历的顺序为:左子树、根节点、右子树。其递归模板如下:

def inorder_recursive(root):
  if root is None:
    return

  # 中序遍历左子树
  inorder_recursive(root.left)

  # 访问根节点
  print(root.val)

  # 中序遍历右子树
  inorder_recursive(root.right)

非递归模板同样利用栈,但访问顺序略有不同:

def inorder_iterative(root):
  if root is None:
    return

  stack = []
  current = root

  while current or stack:
    # 将所有左子树压入栈中
    while current:
      stack.append(current)
      current = current.left

    # 访问栈顶元素(左子树最右节点)
    current = stack.pop()
    print(current.val)

    # 访问右子树
    current = current.right

后序遍历

后序遍历的访问顺序为:左子树、右子树、根节点。其递归模板如下:

def postorder_recursive(root):
  if root is None:
    return

  # 后序遍历左子树
  postorder_recursive(root.left)

  # 后序遍历右子树
  postorder_recursive(root.right)

  # 访问根节点
  print(root.val)

非递归模板则利用了两个栈:

def postorder_iterative(root):
  if root is None:
    return

  stack1 = [root]
  stack2 = []

  while stack1:
    # 将栈1中的元素依次压入栈2中
    node = stack1.pop()
    stack2.append(node)

    # 将左子树和右子树压入栈1if node.left:
      stack1.append(node.left)
    if node.right:
      stack1.append(node.right)

  # 访问栈2中的元素(后序遍历顺序)
  while stack2:
    node = stack2.pop()
    print(node.val)

总结

通过学习本文中提供的模板,您可以轻松掌握二叉树的前序、中序和后序遍历,无论采用递归还是非递归方式。无论是算法设计还是数据结构应用,这些遍历方法都至关重要,它们将助您在二叉树的世界中如鱼得水。