Tree Structure Visualizer

This is a simple tree structure visualizer that allows you to see how different versions of traversal navigate through a tree structure.

Traverse - click to choose an order


Depth Control - control "height" (1-4)


Depth: 3

What is a tree?

A tree is a non-linear data structure that consists of nodes connected by edges. The top node is called the root node, and each node can have zero or more child nodes. The nodes without any children are called leaf nodes. Trees have many applications, including representing the DOM in web development, file systems, and search algorithms like binary search trees.

What is traversal?

Traversal is the process of visiting all the nodes in a tree data structure. There are different ways to traverse a tree, and the most common ones are pre-order, in-order, post-order, and level-order traversal.

How does traversal work?

Traversal works by visiting each node in a tree structure and recursively traversing through the left and right subtrees. The order in which the nodes are visited depends on the type of traversal being used.

Different types of traversal

Pre-Order Traversal

Pre-order traversal visits the root node first, then the left subtree, and finally the right subtree.

// Pre-order traversal
function preOrder(root) {
  if (!root) return;
  console.log(root.value);
  preOrder(root.left);
  preOrder(root.right);
}

In-Order Traversal

In-order traversal visits the left subtree first, then the root node, and finally the right subtree.

// In-order traversal
function inOrder(root) {
  if (!root) return;
  inOrder(root.left);
  console.log(root.value);
  inOrder(root.right);
}

Post-Order Traversal

Post-order traversal visits the left subtree, then the right subtree, and finally the root node.

// Post-order traversal
function postOrder(root) {
  if (!root) return;
  postOrder(root.left);
  postOrder(root.right);
  console.log(root.value);
}

Level-Order Traversal (BFS)

Level-order traversal visits the nodes level by level, starting from the root node. It makes use of a queue to keep track of the nodes. This is also known as Breadth-First Search (BFS).

// Level-order traversal
function levelOrder(root) {
  if (!root) return [];
  let queue = [root], result = [];
  while (queue.length) {
    let node = queue.shift();
    result.push(node.value);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  return result;
}