Inorder Preorder Postorder Traversals

Recursive inorder, preorder, and postorder walks visit a binary tree in three different orders, and a deque drives the level-order variant.

PythonData Integrity

Code

pythonsnippet
54 lines
from collections import deque


class TreeNode:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right


def inorder(node, out):
    # 中序:左 -> 根 -> 右(BST 上即升序)
    if node:
        inorder(node.left, out)
        out.append(node.value)
        inorder(node.right, out)


def preorder(node, out):
    # 前序:根 -> 左 -> 右(适合复制或序列化树形)
    if node:
        out.append(node.value)
        preorder(node.left, out)
        preorder(node.right, out)


def postorder(node, out):
    # 后序:左 -> 右 -> 根(自底向上求值或删除)
    if node:
        postorder(node.left, out)
        postorder(node.right, out)
        out.append(node.value)


def level_order(root):
    # 层序:队列逐层展开
    out, queue = [], deque([root] if root else [])
    while queue:
        node = queue.popleft()
        out.append(node.value)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return out


tree = TreeNode('D',
                TreeNode('B', TreeNode('A'), TreeNode('C')),
                TreeNode('F', TreeNode('E'), TreeNode('G')))

for walk in (inorder, preorder, postorder):
    seen = []
    walk(tree, seen)
    print(f'{walk.__name__}: {" ".join(seen)}')
print('level_order:', ' '.join(level_order(tree)))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

inorder: A B C D E F G
preorder: D B A C F E G
postorder: A C B E G F D
level_order: D B F A C E G

Inorder Preorder Postorder Traversals: how the code works

The working surface is the class TreeNode and the functions __init__, inorder, preorder and postorder — everything else is wiring.

A single loop drives the file — while queue.

The input out is mutated in place — callers that need the original must pass a copy.

What to watch for

  • Runs on the standard library alone; nothing to install.
  • out is mutated in place — the value you pass will not be the same afterward.

Using it

The single function definition: def inorder(node, out)

The demo output is labeled (level_order:); the label names the operation responsible for the line.

inorder is the public entry point; everything else in the file exists to support it.

Key statements

def __init__(self, value, left=None, right=None):
    self.value, self.left, self.right = value, left, right
def postorder(node, out):
    # 后序:左 -> 右 -> 根(自底向上求值或删除)
    if node:
        postorder(node.left, out)
        postorder(node.right, out)
        out.append(node.value)
def preorder(node, out):
    # 前序:根 -> 左 -> 右(适合复制或序列化树形)
    if node:
        out.append(node.value)
        preorder(node.left, out)
        preorder(node.right, out)

Interactive Tools for This Topic

FAQ

Does `inorder` modify its input?
Yes — `out` is mutated in place. Pass a copy if the caller needs the original preserved.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `collections`. The file defines `__init__`, `inorder`, `preorder` at load time.