The Diameter of Binary Tree coding problem asks you to find the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path is the number of edges between the nodes.
This is a "bread and butter" tree question at companies like Apple, Meta, and Amazon. It tests your mastery of the depth-first search interview pattern and your ability to solve a global problem by aggregating local information. It requires you to calculate two things at each node: the height of the subtree (to pass to the parent) and the diameter passing through the node (to update a global max).
This problem uses Recursive DFS (Post-order Traversal).
height(node) that returns the height of the tree rooted at node.height(left_child) + height(right_child).maxDiameter and update it at every node using the sum above.max(left_height, right_child) + 1 to the parent.Tree:
1
/
2 3
/
4 5
maxDiameter = 2. Return height=2.maxDiameter = 3.
Result: 3. (Path: 4-2-1-3 or 5-2-1-3).When you need to return one value (height) but track another (diameter), always use a global variable or pass an object/array by reference. This "Bottom-up Aggregation" is a vital pattern for tree problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Balanced Binary Tree | Easy | Solve | |
| Leaf-Similar Trees | Easy | Solve | |
| Sum of Root To Leaf Binary Numbers | Easy | Solve | |
| Evaluate Boolean Binary Tree | Easy | Solve | |
| Second Minimum Node In a Binary Tree | Easy | Solve |