Diameter of Binary Tree

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Diameter of Binary Tree

Approach

During depth-first traversal, update diameter as leftHeight + rightHeight at each node and return max subtree height.

Complexity Analysis

Time
O(n) where n is node count
Space
O(h) where h is tree height

Pattern

Tree DP via DFS

Why It Works

Each node contributes a candidate diameter through its left and right heights.

Updated Feb 2026