48. Diameter of Binary Tree

48. Diameter of Binary Tree

Medium
57.0%
2.0k
dfstreebinary-treerecursion
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A large-scale platform models hierarchical relationships such as service dependencies, call graphs, org structures, or feature trees using a binary tree.

For performance analysis and reliability planning, the platform wants to know the longest possible “chain” in the structure. This helps estimate:

  • worst-case dependency depth
  • longest call path for latency analysis
  • maximum propagation distance for alerts
  • stress testing of recursive processing

In tree terms, this “longest chain” is called the diameter: the length of the longest path between any two nodes in the tree. The path may or may not pass through the root.

This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given the root of a binary tree, return the diameter of the tree.

The diameter is defined as the number of edges in the longest path between any two nodes.

Input Format

  • root: the root node of a binary tree

Each node is defined as:

TreeNode { int val; TreeNode left; TreeNode right; }

Output Format

  • A single integer representing the diameter (in number of edges)

Examples

Example 1:

Input: root = [1,2,3,4,5]
Output: 3
Explanation: The longest path is 4 -> 2 -> 1 -> 3, which has 3 edges.

Example 2:

Input: root = [1,2]
Output: 1

Example 3:

Input: root = []
Output: 0

Constraints

  • 0 <= number of nodes <= 100,000
  • -10^9 <= Node.val <= 10^9

Loading editor...

[1,2,3,4,5]
3

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback