Tree
Example
function depth(node) {
return 1 + Math.max(depth(node.left), depth(node.right));
}function depth(node) {
if (node === null) return 0;
return 1 + Math.max(depth(node.left), depth(node.right));
}Without the base case the function reads left of null and throws a 'TypeError'.
Common mistakes
- Assuming a binary search tree stays O(log n) when the inserted data is sorted.
- Recursing into children without a
nullcheck.
Key points
- Recursive traversal returns at a
nullnode before reading its children. - Binary search tree cost is stated as O(h), which is O(n) when the tree is unbalanced.
- Very deep trees use an iterative traversal with an explicit stack to avoid stack overflow.
Interview questions
Tree vs graph: what is the difference?
A tree is a connected graph with no cycles: n nodes and exactly n - 1 edges, with one path between any two nodes. A graph can have cycles and disconnected parts.
What is the height of a tree?
The number of edges on the longest path from the root to a leaf. A balanced binary tree with n nodes has height O(log n).
What are the tree traversal orders?
Depth-first orders are preorder, inorder and postorder. Level order visits nodes level by level, which is breadth-first search.