返回

二叉树深度优先 之 先中后序遍历

前端

算法概览
深度优先遍历, 简称 DFS, 其算法概览如下:

  • 从根节点开始, 将其压入栈中
  • 从栈中取出一个节点, 并访问它
  • 将该节点的所有子节点从左到右依次压入栈中
  • 重复步骤2和步骤3, 直到栈为空

先序遍历

先序遍历, 即在访问父节点之前先访问其子节点。其算法实现如下:

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

    stack = [root]
    while stack:
        node = stack.pop()
        visit(node)
        if node.right is not None:
            stack.append(node.right)
        if node.left is not None:
            stack.append(node.left)

中序遍历

中序遍历, 即在访问父节点之前先访问其左子节点, 然后访问其右子节点。其算法实现如下:

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

    stack = []
    while stack or root:
        if root:
            stack.append(root)
            root = root.left
        else:
            root = stack.pop()
            visit(root)
            root = root.right

后序遍历

后序遍历, 即在访问父节点之前先访问其左子节点和右子节点。其算法实现如下:

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

    stack = [root]
    last_visited = None
    while stack:
        node = stack[-1]
        if last_visited is None or last_visited.left == node or last_visited.right == node:
            if node.left:
                stack.append(node.left)
            elif node.right:
                stack.append(node.right)
        else:
            visit(node)
            stack.pop()
            last_visited = node

应用场景

深度优先遍历可以应用于各种场景, 比如:

  • 二叉树的节点计数
  • 二叉树的高度计算
  • 二叉树中是否存在某一节点
  • 二叉树的镜像翻转
  • 二叉树的前缀表达式的生成

结论

在本文中, 我们讨论了二叉树深度优先遍历的三种非递归实现, 包括先序遍历, 中序遍历和后序遍历。每种遍历方式都有其独特的应用场景。读者可以根据自己的需要选择合适的遍历方式。