What is the difference between depth and height of a tree?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Data Structures & Algorithms basics — a prerequisite for any developer role.
Answer
Depth of a node is the number of edges from the root to that node. The root has depth 0. A node at depth d has d edges between it and the root. Height of a node is the number of edges on the longest path from that node down to a leaf. A leaf node has height 0. The height of the tree is the height of the root node (equivalently, the depth of the deepest leaf). Example: in a tree with root A (depth 0, height 3), child B (depth 1, height 2), grandchild C (depth 2, height 1), great-grandchild D (depth 3, height 0 — leaf). Note: some sources define height as number of nodes instead of edges (height = depth + 1) — clarify in interviews. Height of a balanced binary tree with n nodes: O(log n). Height of a degenerate (skewed) tree: O(n). Level: depth + 1 (so root is at level 1). Calculating height recursively: height(null) = -1; height(node) = 1 + max(height(node.left), height(node.right)). A balanced tree: for every node, |height(left) - height(right)| ≤ 1. AVL trees maintain this property strictly; Red-Black trees maintain approximate balance.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Data Structures & Algorithms answers easy to follow.