温馨提示×

如何实现TreeNode的非递归遍历

小樊
81
2024-09-03 12:07:16
栏目: 编程语言

要实现TreeNode的非递归遍历,可以使用迭代方法和栈数据结构。这里以二叉树的前序遍历、中序遍历和后序遍历为例进行说明。

首先定义一个简单的TreeNode类:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
  1. 前序遍历(根 -> 左 -> 右)
def preorder_traversal(root):
    if root is None:
        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
  1. 中序遍历(左 -> 根 -> 右)
def inorder_traversal(root):
    if root is None:
        return []

    stack, result = [], []
    current = root

    while current or stack:
        while current:
            stack.append(current)
            current = current.left

        current = stack.pop()
        result.append(current.val)
        current = current.right

    return result
  1. 后序遍历(左 -> 右 -> 根)
def postorder_traversal(root):
    if root is None:
        return []

    stack, result = [root], []

    while stack:
        node = stack.pop()
        result.append(node.val)

        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)

    return result[::-1]  # 反转列表得到正确的后序遍历顺序

这样就实现了二叉树的非递归遍历。注意这里的遍历顺序与递归遍历相同,只是实现方式不同。

0