Trees & Traversals

Hierarchical data — terminology, binary trees, and the four traversals every engineer must know cold.

Beginner 3 min readLesson 7 of 16 Interview Q&A

A tree is a hierarchy of nodes connected by edges, with one root and no cycles. File systems, the HTML DOM, org charts, JSON, abstract syntax trees, database indexes and decision trees are all trees.

DEBFCA
A tree with root A. B and C are A's children; D, E, F are leaves.

Vocabulary

TermMeaning
RootThe top node (no parent)
Parent / childDirectly connected nodes, one level apart
LeafA node with no children
SubtreeA node plus all its descendants
Depth of a nodeEdges from the root to it (root depth = 0)
Height of a nodeEdges on the longest path down to a leaf
DegreeNumber of children

A tree with n nodes always has exactly n − 1 edges.

Binary trees

Each node has at most two children: left and right.

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}

Shapes worth naming

  • Full — every node has 0 or 2 children.
  • Complete — every level full except possibly the last, which fills left to right. Heaps are complete, so they fit in an array.
  • Perfect — all internal nodes have 2 children and all leaves share a depth: 2^(h+1) − 1 nodes.
  • Balanced — subtree heights differ by a small amount everywhere → height O(log n).
  • Degenerate — every node has one child; really a linked list with height n − 1.

The four traversals

452631
Example tree (level order: 1, 2, 3, 4, 5, null, 6)
TraversalOrderResultTypical use
Pre-ordernode, left, right1 2 4 5 3 6Copy / serialize a tree
In-orderleft, node, right4 2 5 1 3 6BST → sorted order
Post-orderleft, right, node4 5 2 6 3 1Delete a tree, compute sizes/heights
Level-order (BFS)level by level1 2 3 4 5 6Shortest path, level views

Pre/in/post-order are depth-first. Recursive versions are three lines; the only difference is where you visit the node.

void preorder(TreeNode n, List<Integer> out) {
    if (n == null) return;
    out.add(n.val);              // visit BEFORE children
    preorder(n.left, out);
    preorder(n.right, out);
}

void inorder(TreeNode n, List<Integer> out) {
    if (n == null) return;
    inorder(n.left, out);
    out.add(n.val);              // visit BETWEEN children
    inorder(n.right, out);
}

// Iterative in-order with an explicit stack
List<Integer> inorderIter(TreeNode root) {
    List<Integer> out = new ArrayList<>();
    Deque<TreeNode> st = new ArrayDeque<>();
    TreeNode cur = root;
    while (cur != null || !st.isEmpty()) {
        while (cur != null) { st.push(cur); cur = cur.left; }
        cur = st.pop();
        out.add(cur.val);
        cur = cur.right;
    }
    return out;
}

List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    Queue<TreeNode> q = new ArrayDeque<>();
    if (root != null) q.offer(root);
    while (!q.isEmpty()) {
        List<Integer> level = new ArrayList<>();
        for (int i = q.size(); i > 0; i--) {     // exactly one level
            TreeNode n = q.poll();
            level.add(n.val);
            if (n.left != null) q.offer(n.left);
            if (n.right != null) q.offer(n.right);
        }
        res.add(level);
    }
    return res;
}

All traversals are O(n) time. Space is O(h) for DFS (recursion/stack depth) and O(w) for BFS (the widest level).

Thinking recursively about trees

Most tree problems follow one recipe: solve for the left subtree, solve for the right subtree, combine with the current node.

Height and diameter
int height(TreeNode n) {
    if (n == null) return 0;                 // counts nodes; use -1 to count edges
    return 1 + Math.max(height(n.left), height(n.right));
}

int best = 0;
int diameterOfBinaryTree(TreeNode root) { depth(root); return best; }
int depth(TreeNode n) {
    if (n == null) return 0;
    int l = depth(n.left), r = depth(n.right);
    best = Math.max(best, l + r);            // longest path THROUGH n
    return 1 + Math.max(l, r);               // longest path DOWN from n
}
Key takeaways
  • Trees are acyclic hierarchies; n nodes ⇒ n − 1 edges.
  • Know pre/in/post-order (DFS) and level-order (BFS), recursively and iteratively.
  • Traversals are O(n) time; DFS space is O(height), BFS space is O(width).
  • Solve tree problems by combining answers from subtrees.
Interview questions
QCan you rebuild a binary tree from its traversals?medium

Pre-order + in-order (or post-order + in-order) uniquely determine a tree with distinct values: the first pre-order element is the root; its position in the in-order sequence splits the left and right subtrees. Use a value→index map for O(n). Pre-order + post-order alone are ambiguous.

QFind the lowest common ancestor of two nodes in a binary tree.medium

Recurse: if the node is null or equals p or q, return it. Recurse left and right; if both return non-null, this node is the LCA; otherwise return whichever is non-null. O(n).

QHow do you traverse a tree in O(1) extra space?hard

Morris traversal: temporarily point the in-order predecessor's right pointer back to the current node ("threading"), walk down, and remove the thread on the second visit. O(n) time, O(1) space, and the tree is restored.