Skip to article content
FrontendXLesson 13 / 24

Trees and traversal

Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.

intermediate · about 35 minutes · 3 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Describe a binary tree and its depth and height.
  • Write preorder, inorder and postorder traversals recursively.
  • Perform level-order traversal with a queue.

Overview

#

Tree vocabulary

A tree is a set of nodes where each node has child nodes and exactly one parent, except the root. A binary tree allows at most two children per node. The depth of a node is the number of edges from the root; the height of the tree is the largest depth.

snippet.txt
class TreeNode {
  constructor(value) { this.value = value; this.left = null; this.right = null; }
}

Depth-first traversal

Depth-first traversal visits a node and then its subtrees. The order of the visit relative to the recursive calls gives three variants:

snippet.txt
function preorder(node, out = []) {
  if (!node) return out;
  out.push(node.value);
  preorder(node.left, out);
  preorder(node.right, out);
  return out;
}
  • Preorder: node, left, right. Useful for copying a tree.
  • Inorder: left, node, right. On a binary search tree this yields sorted order.
  • Postorder: left, right, node. Useful when children must be processed before the parent.

Breadth-first traversal

Level-order uses a queue so nodes are visited by increasing depth:

snippet.txt
function levelOrder(root) {
  if (!root) return [];
  const out = [];
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    out.push(node.value);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  return out;
}

Choosing a traversal

Use depth-first when the answer for a node depends on its subtrees, such as height or path sums. Use breadth-first when the answer depends on distance from the root, such as the shallowest target or level averages.

Practice next

  • Compute the maximum depth of a binary tree recursively.
  • Return the values of each level as a list of lists.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    For a tree with root 2, left child 1 and right child 3, what does inorder traversal output?

    starter.javascript
    // inorder: left, node, right

    Reveal the reference answer
    reference.javascript
    Visit left (1), then the node (2), then right (3), giving [1, 2, 3].

    Authored expected output: [1, 2, 3]

    This tree is also a binary search tree, so inorder is sorted.

  2. Exercise 2Implement

    Implement maxDepth(root) that returns the number of nodes on the longest root-to-leaf path.

    starter.javascript
    function maxDepth(root) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function maxDepth(root) {
      if (!root) return 0;
      return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

    Authored expected output: 3 for a three-level tree

    Each node contributes one level plus the deeper of its two subtrees.

  3. Exercise 3Explain

    Explain why level-order traversal uses a queue while preorder traversal uses a stack or recursion.

    Reveal the reference answer
    reference.text
    Level-order must finish all nodes at one depth before starting the next, which is first-in-first-out order, so a queue is natural. Preorder dives into a subtree before its sibling, which is last-in-first-out order, so a stack or the call stack is natural.

    Authored expected output: Level order is FIFO; depth-first is LIFO.

    The traversal order determines the data structure.

Common misconceptions

#
  • Inorder traversal is sorted for any binary tree. It is sorted only for a binary search tree.
  • Breadth-first is faster than depth-first. Both visit every node once; they differ in order and space.
  • Tree traversal needs recursion. An explicit stack or queue does the same work.

Follow-up practice

#
  • dsa-from-zero-binary-search-trees
  • dsa-from-zero-heaps-and-priority-queues
  • dsa-from-zero-graphs-and-traversal

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.