Prepin
Log in

G

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

Approach / Explanation

This question requires you to determine the longest path between any two nodes in a binary tree, which may or may not include the root. This longest path is referred to as the "diameter" of the tree. Your task is to create a function that returns this diameter, given the root of the binary tree. Here are some key points to consider in your response: The diameter of a binary tree is defined as the length of the longest path between any two nodes in the tree, which may or may not include the root. A path between two nodes consists of a series of consecutive edges connecting the source node to the destination node. The length of a path is determined by the total number of nodes along that path. A crucial observation is that the diameter of a tree T will always be the greatest among these three options: the diameter of T’s right subtree, the diameter of T’s left subtree, the longest path between leaves that passes through the root of T, which is the combined heights (number of nodes in the longest path) of the left and right subtrees. Therefore, the essential approach is to use depth-first search to calculate the heights of the left and right subtrees for each node and then update the maximum diameter encountered so far.

Suggested Answer

Below is a Python implementation of the function: class Solution : def diameterOfBinaryTree ( self , root ) : self . diameter = 0 def depth ( node ) : if not node : return 0 left = depth ( node . left ) right = depth ( node . right ) self . diameter = max ( self . diameter , left + right ) return max ( left , right ) + 1 depth ( root ) return self . diameter The depth function serves as a recursive helper that calculates the depth of the tree with its root at node while simultaneously updating the diameter.

Alternative Answer

Below is the Java implementation of the function: public class Solution { int ans ; public int diameterOfBinaryTree ( TreeNode root ) { ans = 1 ; depth ( root ) ; return ans - 1 ; //we return the number of edges, not nodes, so subtract 1 } public int depth ( TreeNode node ) { if ( node == null ) return 0 ; int left = depth ( node . left ) ; int right = depth ( node . right ) ; ans = Math . max ( ans , left + right + 1 ) ; return Math . max ( left , right ) + 1 ; } } This method follows the same logic as the Python example. We are determining the maximum diameter encountered so far ( ans ) along with the potential maximum diameter that includes the current node, calculated as left+right+1 . Finally, we return the depth of the tree originating from node plus one.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Amazon
Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.