All algorithms
Trees

Binary Tree Traversal

In-order, pre-order, post-order — where the visit sits in the recursion.

TimeO(n)SpaceO(h)CategoryTrees

The three classic traversals differ by exactly one thing: where the visit happens relative to the two recursive calls. Pre-order visits before descending, in-order visits between the left and right calls, post-order visits after both return.

On a binary search tree, in-order yields the keys in sorted order — which is the fastest way to check that a tree really is a BST. Post-order is what you need when children must be handled before their parent, as in deleting a tree or computing subtree sums.

The recursion is easy to write and hard to picture. AlgoLens draws the tree together with the call stack, so you see the descent, the visit, and the unwind as three separate moments.

The code

tree_traversal.cpp
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int val;
    Node* left;
    Node* right;
    Node(int v) : val(v), left(nullptr), right(nullptr) {}
};

void inorder(Node* node) {
    if (!node) return;
    inorder(node->left);
    cout << node->val << ' ';
    inorder(node->right);
}

int main() {
    Node* root = new Node(4);
    root->left = new Node(2);
    root->right = new Node(6);
    root->left->left = new Node(1);
    root->left->right = new Node(3);
    root->right->left = new Node(5);

    inorder(root);
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Binary Tree Traversal

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going