Compile Ready
Module 1 · Tree Fundamentals

Depth

Depth measures how far a node is from the root, so it is naturally computed top-down or level-by-level rather than by aggregating child answers.

7 min readConcept
TreeDepthBFS

Definition and Level Convention

The depth of a node is the number of edges from the root down to that node. The root has depth 0. Its children have depth 1. Their children have depth 2, and so on. Many interviewers use the word level for the same idea, though some one-index levels in UI descriptions; always clarify the starting value.

For [3,9,20,null,null,15,7], node 3 is depth 0, nodes 9 and 20 are depth 1, and nodes 15 and 7 are depth 2.

Top-Down Computation

Depth is top-down because the answer is carried from the root to the current node. A recursive helper receives the current depth, processes the node, then calls the left and right children with depth + 1.

This direction is the opposite of height. The child does not need to inspect its descendants to know its depth; it only needs to know how far its parent already was from the root.

Level-Order Framing

Breadth-first search makes depth visible as levels. Put the root in a queue at depth 0. Process exactly the current queue size to finish one level, then enqueue children for the next level. After one full layer is consumed, the depth counter increases.

This framing is useful for problems that ask for right side view, averages by level, zigzag order, minimum depth, or nearest target. If the prompt is about levels, a queue is often more natural than recursion.

Height vs Depth

Height and depth are classic interview confusion points. Depth looks upward to the root and counts how many edges were used to reach the node. Height looks downward to the deepest leaf and counts how much subtree remains below the node.

A leaf can have large depth and height 0 at the same time. In a long skewed tree, the last node is far from the root, so its depth is large, but it has no children, so its height is 0. Keeping the direction clear prevents off-by-one and wrong-traversal bugs.

Key Takeaways

  • Depth is the number of edges from the root to a node, with root depth **0**.
  • Depth is naturally top-down: pass **depth + 1** from parent to children.
  • BFS processes one queue layer per depth, which matches level-order problems.
  • Depth counts distance from the root; height counts distance down to the deepest leaf.