Data Structures19 sections · 729 units
Open in Course

Recursive Traversal

The natural approach

Recursive traversal is clean and intuitive:

function preorder(node):
    if node == null: return
    process(node.val)
    preorder(node.left)
    preorder(node.right)

function inorder(node):
    if node == null: return
    inorder(node.left)
    process(node.val)
    inorder(node.right)

function postorder(node):
    if node == null: return
    postorder(node.left)
    postorder(node.right)
    process(node.val)

Time complexity: O(n)O(n). Each node is visited exactly once.

Space complexity: O(h)O(h) for the call stack, where hh is tree height.

In the worst case (skewed tree), h=nh = n, so space is O(n)O(n). For balanced trees, space is O(logn)O(\log n).