00:00

Problem Statement

Input/Output Examples

Visual Explanation

The recursion reaches the leaves first and combines the answers on the way back up, so every node is visited exactly once.

Approaches

Depth-first recursion is the shortest solution. Breadth-first search counts the levels instead.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of nodes. Both approaches visit every node once; DFS needs stack space for the height, BFS needs queue space for the widest level.

Interview Tips and Recommended Approach

  • Agree on the definition. Some problems count edges instead of nodes; the edge-based depth is one less.
  • Handle the empty tree. Returning 0 for null makes the recursion work for leaves too.
  • Mention stack depth. A tree shaped like a linked list can make recursion very deep.
  • Reuse the pattern. Balanced-tree checks and the diameter problem build on this height function.

Recommended Approach: Recursive DFS

Why: it is three lines long, visits each node once and mirrors the definition of depth exactly.