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)