00:00

Problem Statement

Input/Output Examples

Visual Explanation

Heights are counted in nodes, so the number of edges on the path through a node is exactly left height plus right height. Recording the best value while computing heights needs only one traversal.

Approaches

The one-pass DFS computes heights and the diameter together. The brute force recomputes heights for every node.

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 and h the height. The one-pass version visits each node once; the brute force can visit each node once per ancestor.

Interview Tips and Recommended Approach

  • Count edges, not nodes. Make sure the answer for a single node is 0.
  • Do not assume the path uses the root. In a tree with a large left subtree, the longest path can stay inside it.
  • Avoid the repeated-height trap. Calling a separate height function at every node makes it quadratic.
  • Avoid static state in real code. Use a field, an array of size 1 or a small result object instead of a static variable if the method must be thread-safe.

Recommended Approach: One-Pass DFS

Why: it finds the diameter in a single traversal by reusing the heights it already computes.