Skip to content

Visualizers

Tree Traversals Visualizer

Step-through BST traversals: Inorder, Preorder, and Postorder.

native (SVG) Client-side

Traversal Output

Select traversal type and click Traverse.

Execution Log

Current Action:

Idle

Complexity Details:

Time: $O(n)$ (Visits every node exactly once)

Space: $O(h)$ (Stack space proportional to tree height)

Binary Tree Traversals

Unlike linear data structures (arrays, linked lists) which have only one logical way to traverse them, trees can be traversed in different ways. Depth-First Traversals are categorized by the order in which the root node is visited relative to its children.

Depth-First Traversal Styles

  • Inorder (Left, Root, Right): Visited left subtree, then root, then right subtree. For a BST, this visits nodes in ascending order.
  • Preorder (Root, Left, Right): Visited root first, then left subtree, then right subtree. Useful for copying a tree structure.
  • Postorder (Left, Right, Root): Visited left subtree, then right subtree, then root. Useful for deleting a tree or evaluating postfix expressions.

Implementation

// Preorder (Root, Left, Right)
function preorder(node) {
  if (!node) return;
  console.log(node.val);
  preorder(node.left);
  preorder(node.right);
}

// Inorder (Left, Root, Right)
function inorder(node) {
  if (!node) return;
  inorder(node.left);
  console.log(node.val);
  inorder(node.right);
}

// Postorder (Left, Right, Root)
function postorder(node) {
  if (!node) return;
  postorder(node.left);
  postorder(node.right);
  console.log(node.val);
}