The Complete Tree Crash Course
Tree problems are among the most frequent questions in coding interviews.
Start with the vocabulary:
1) Tree Vocabulary
- Root
- Leaf
- Child
- Subtree
- Height
- Depth
- Ancestor
- Descendant
The tree you will meet most often in interviews is the binary tree.
In a binary tree every node has at most two children, called the left child and the right child.
Every node also stores a value of its own.
Traversal Methods
1) Depth First Search
Follows one branch as deep as it goes before backing up to try the next.
- Preorder
- Inorder
- Postorder
The three orders differ only in when you process the current node: before, between or after its subtrees.
Recursive DFS is short to write, so expect a follow up asking for the iterative version with a stack.
2) Breadth First Search
Visits the tree one level at a time, from the root down, using a queue.
Reach for it whenever a problem talks about levels, such as the right side view or the minimum depth.
3) Binary Search Tree (BST)
A binary search tree keeps its values in order, which makes searching fast.
Every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. Most interview versions assume there are no duplicates.
An inorder traversal of a BST visits the values in sorted order.
Know these by heart:
- Search for a value, and handle the value being missing
- Insert a value
- Delete a node with zero, one or two children
4) Kinds of Binary Trees
These names come up in problem statements.
Knowing them tells you which guarantees you can rely on, for example that a complete tree fits neatly into an array.
- Full binary tree
- Complete binary tree
- Perfect binary tree
- Balanced binary tree
- Degenerate binary tree
5) Specialized Trees
- Heap
- N-ary tree
- Trie (prefix tree)
- Segment tree
NOTES
- Most tree solutions are recursive, so make sure you are comfortable with recursion first.
- If a recursive solution feels obvious, practice converting it to an iterative one with an explicit stack or queue.
- The height of a balanced tree is O(log n), but a degenerate tree can be O(n) tall, which changes the complexity.
- Interviewers rarely ask you to implement a self balancing tree, but they do expect you to know what balanced means.