Binary Tree Traversals

Tree Selection

Traversal Method

• Left subtree → Root → Right subtree

Playback Controls

Select a tree and traversal method to begin

Traversal Methods

Use Cases:

  • Inorder: BST → sorted sequence
  • Preorder: Copy/serialize tree
  • Postorder: Delete tree, calculate size
  • Level Order: Print by levels, BFS

Legend:

Current (Inorder)
Current (Preorder)
Current (Postorder)
Current (Level Order)
Children/Subtree

Reference implementation of Binary Tree Traversals. Select a language tab to view and copy the code.

def inorder(root):
    if root is None: return
    inorder(root.left)          # traverse left subtree
    visit(root)                  # process current node
    inorder(root.right)         # traverse right subtree

def preorder(root):
    if root is None: return
    visit(root)                  # process current node first
    preorder(root.left)         # traverse left subtree
    preorder(root.right)        # traverse right subtree

def postorder(root):
    if root is None: return
    postorder(root.left)        # traverse left subtree
    postorder(root.right)       # traverse right subtree
    visit(root)                  # process current node last

def level_order(root):
    if root is None: return
    queue = deque([root])        # start with root
    while queue:
        node = queue.popleft()   # dequeue front node
        visit(node)              # process current node
        if node.left:  queue.append(node.left)
        if node.right: queue.append(node.right)

Python — Code Walkthrough

  1. Inorder (Left → Root → Right)

    inorder(root.left) → visit(root) → inorder(root.right)

    Visits left subtree first, then the current node, then right. For a BST this produces sorted order.

  2. Preorder (Root → Left → Right)

    visit(root) → preorder(root.left) → preorder(root.right)

    Visits the current node before its children. Useful for copying or serializing a tree.

  3. Postorder (Left → Right → Root)

    postorder(root.left) → postorder(root.right) → visit(root)

    Visits both children before the current node. Used for deletion — children are freed before the parent.

  4. Level Order — queue-based BFS

    queue = deque([root]); node = queue.popleft()

    Processes nodes level by level using a FIFO queue. Each dequeued node is visited and its children are enqueued.