Skip to content
Tech Interview Prep
Technical interview guide

Trees

Hierarchical node structures built on the same pointer discipline as linked lists, traversed via recursion or an explicit stack/queue.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with ordered-map guarantees cited from the C++ standard containers and java.util as of Java 21.

Overview

Curated: · Written: · Reviewed:

Trees

In one line

A tree is a node whose children are trees, so most tree algorithms are a base case for a null node, recursive calls on the children, and a combination step. Reach for a binary search tree when you need ordered or range queries over keys, and only quote logarithmic cost if the tree is balanced, because sorted input turns a plain BST into a list.

Key definitions

  • Depth: edges from the root down to a node. Known on the way down, so it is passed as a parameter.
  • Height: edges on the longest downward path to a leaf (a leaf has height 0). Known on the way up, so it is returned.
  • Ordering invariant: every key in the left subtree is smaller than the node, and every key in the right subtree is larger. It constrains whole subtrees.
  • Inorder successor: the leftmost node of the right subtree, used to replace a node that has two children.
  • Balance condition: the rule (AVL height difference at most 1, red-black no path more than twice another, B-tree uniform depth) that keeps height logarithmic.
  • Threaded link: a temporary right pointer to an inorder successor, as used by the Morris traversal.

Formulas and complexity

search, insert, delete=O(h),h≥⌊log⁡2n⌋\text{search, insert, delete} = O(h), \quad h \ge \lfloor \log_2 n \rfloor sorted keys into a plain BST: h=n−1 (65,536 keys give a 65,535-edge path)\text{sorted keys into a plain BST: } h = n - 1 \text{ (65,536 keys give a 65,535-edge path)} ordered tree map: get O(log⁡n), floor/ceiling O(log⁡n), range O(log⁡n+k)\text{ordered tree map: get } O(\log n), \text{ floor/ceiling } O(\log n), \text{ range } O(\log n + k) complete-tree array: a chain of d left children below the root needs 2d slots\text{complete-tree array: a chain of } d \text{ left children below the root needs } 2^{d} \text{ slots} red-black lookup on 16 million keys≈log⁡2(16×106)≈24 page reads; B-tree, fanout 256: ⌈log⁡256(16×106)⌉=3\text{red-black lookup on 16 million keys} \approx \log_2(16\times10^6) \approx 24 \text{ page reads; B-tree, fanout 256: } \lceil \log_{256}(16\times10^6) \rceil = 3

How it works

  • Each recursive call handles one node: return the base value for null, recurse on the children, then combine. Depth flows down as a parameter and height flows up as a return value.
  • A BST search follows one edge per comparison, so its cost is the length of the path it walks, which is h.
  • A rotation relinks a constant number of nodes and keeps the inorder sequence unchanged, so balance is restored without breaking the ordering invariant.
5 root 1 6 4 invalid: under 5's right subtree 7

When to use and when not to

SituationChooseWhy
Exact-key lookup onlyHash mapO(1) expected; no ordering is used
Floor, ceiling, range, ordered iterationOrdered tree mapHash map needs a full scan
Data that is hierarchical (parent and child)TreeThe hierarchy is the model
Keys inserted in sorted order into a plain BSTNeither as writtenHeight becomes n; use a balanced tree
Ordered map in productionLibrary ordered mapDeletion is where hand-written trees fail
Memory-constrained, single thread, need O(1) extra spaceMorris traversalMutates the tree while it runs

Traps interviewers probe

  1. Quoting O(log n) for a search tree without the balance condition. Fix: state the cost as O(h), then say what makes h logarithmic. Sorted insertion of 65,536 keys makes the lookup for the largest key take 65,536 comparisons.
  2. Validating only that each node sits between its children. Fix: carry an open (low, high) interval down the recursion, narrowing it at each node. A deep node in the right subtree can be smaller than the root.
  3. Returning 0 for a null child in max or sum code. Fix: a 0 from an absent child beats every negative value, so tree_max over all-negative keys returns 0. Return negative infinity for the null case, or start from the first real node.
  4. Returning the turning path to the parent in path sum or diameter. Fix: return the best one-sided gain to the parent, and record the candidate that turns at the node in a separate global. The diameter does not need to pass through the root.
  5. Running Morris traversal while readers search the tree. Fix: the traversal threads right pointers, so a lookup can follow a thread back into a cycle. Lookups for 25 and 45 spin in the guide's example while the job runs, and only single-threaded use is safe.

Interview tips

Open with the structure and the query: 'A BST gives O(h) operations, logarithmic only when the tree is balanced, so for ordered queries I would use the library's ordered map.'

Follow-ups to expect:

  • Validate a BST: inherited open interval, with the counterexample where a deep node violates the root.
  • Delete a node with two children: replace it with the inorder successor (leftmost node of the right subtree), copy its value, then delete the successor. Promoting an arbitrary child breaks the invariant.
  • Serialise a tree: preorder with explicit null markers, or preorder plus inorder. Preorder alone is ambiguous.
  • LCA: descend by key comparisons in a BST; use a postorder report-and-meet on a general binary tree.
  • Recursion limit: an inorder recursion on 50,000 sorted keys raises RecursionError at CPython's default limit of 1000. Switch to an explicit stack.
  • AVL versus red-black: AVL is stricter, so lookups are faster and writes need more rotations. Red-black tolerates more imbalance and rotates less on writes.

30-second answer outline:

  1. Name the structure and the query it serves.
  2. State the cost as O(h), and the balance condition that makes h logarithmic.
  3. Give the invariant and the local-check trap that breaks it.
  4. Say what you would ship: the library ordered map, or a B-tree when the data lives on disk.

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.