543. Diameter of Binary Tree
easyFind the length of the longest path between any two nodes in a binary tree, measured in edges. The path need not pass through the root — solve with single-pass DFS returning depth and updating a global max.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is 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 between two nodes is represented by the number of edges between them.
Constraints
The number of nodes in the tree is in the range [1, 10^4].-100 <= Node.val <= 100
Examples
Example 1
root = [1,2,3,4,5]3Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
Example 2
root = [1,2]1Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
For every node, the longest path THROUGH that node = depth(left) + depth(right).
Hint 2
Take the max of those over all nodes — that's the diameter.
Hint 3
Compute depth with the same DFS that's updating the diameter — one pass total.
Solution approach
Reveal approach
DFS returning depth, updating a global diameter. Helper depth(node): if null return 0; left = depth(node.left); right = depth(node.right); diameter = max(diameter, left + right); return 1 + max(left, right). The diameter variable is updated for every node visited, since each node is the apex of at most one optimal path. Return diameter at the end. O(n) time, O(h) recursion space.
Complexity
- Time
- O(n)
- Space
- O(h)
Related patterns
- dfs
- recursion
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
- Microsoft
More Trees practice problems
- 94. Binary Tree Inorder Traversal
- 98. Validate Binary Search Tree
- 100. Same Tree
- 101. Symmetric Tree
- 102. Binary Tree Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- 104. Maximum Depth of Binary Tree
- 105. Construct Binary Tree from Preorder and Inorder Traversal