Diameter of Binary Tree
Updated
Problem statement
You are given the root of a binary tree. A path in the tree goes from one node to another along the edges between parents and children, and it never visits the same node twice. The length of a path is the number of edges on it.
The diameter of the tree is the length of the longest path between any two nodes. This path may pass through the root, but it does not have to.
Return the diameter of the tree.
Function
diameterOfBinaryTree(root: TreeNode) → intExamples
Example 1
root = [4,2,7,1,3,null,9]return = 4One longest path is 1 -> 2 -> 4 -> 7 -> 9; 3 -> 2 -> 4 -> 7 -> 9 is just as long. Both pass through the root and have 4 edges, so the diameter is 4.
Example 2
root = [1,2,null,3,4,5,null,null,6]return = 4The root 1 has only a left child, 2. The longest path is 5 -> 3 -> 2 -> 4 -> 6, with 4 edges, and it does not use the root. The longest path that does use the root, such as 1 -> 2 -> 3 -> 5, has only 3 edges.
Example 3
root = [-7]return = 0The tree has one node and no edges, so no path can have more than 0 edges. The diameter is 0.
Constraints
- The number of nodes in the tree is in the range
[1, 10^4]. -100 <= Node.val <= 100
More eBay Onsite Interview questions
- Extract Hashtags from a TweetONSITE INTERVIEW · Seen Nov 2026
- Validate Ada Integer LiteralONSITE INTERVIEW · Seen Nov 2026
- Count Distinct Pairs With Sum KONSITE INTERVIEW · Seen Nov 2026
- Count Staircases with Strictly Increasing StepsONSITE INTERVIEW · Seen Oct 2026
- Hierarchical Permission CheckONSITE INTERVIEW · Seen Oct 2026
- Matrix MultiplicationONSITE INTERVIEW · Seen Oct 2026
- N-Queens Solution CountONSITE INTERVIEW · Seen Oct 2026
- Gas StationONSITE INTERVIEW · Seen Oct 2026
- Onion-Peel Layers of a Binary TreeONSITE INTERVIEW · Seen Oct 2026
- Container With Most WaterONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Maximum Depth of Binary TreeLinkedIn · PHONE SCREEN · ONSITE INTERVIEWLinkedIn interview questions
- Symmetric Binary TreeFigma · ONSITE INTERVIEWFigma interview questions
- Tree Level with the Most NodesBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Mirror Image Binary TreesExpedia · ONSITE INTERVIEWExpedia interview questions
- Mirror a Binary TreeAMD · ONSITE INTERVIEWAMD interview questions
- Find a Node’s Level in an N-ary TreeMorgan Stanley · ONSITE INTERVIEWMorgan Stanley interview questions
- Symmetric Binary TreeCapital One · ONSITE INTERVIEWCapital One interview questions
- Serialize and Deserialize a Binary TreeAmazon · ONSITE INTERVIEW
- Delete Nodes and Return Forest RootsGoogle · ONSITE INTERVIEWGoogle interview questions
- Diameter of an Acyclic Undirected GraphSalesforce · ONSITE INTERVIEWSalesforce interview questions