Learn how to calculate the diameter (longest path) of a binary tree in one pass using recursion. Clear, step-by-step code and explanations perfect for LeetCode practice. You can solve the problem by visiting this Problem Link.
What the Problem Asks
LeetCode 543: Diameter of Binary Tree
Given a binary tree, find the length of the diameter of the tree.
The diameter is the number of edges on the longest path between any two nodes in the tree.
Key point: The longest path might go through the root or any other node.
Example Tree:
1
/ \
2 3
/ \
4 5The longest path is 4 → 2 → 1 → 3, which has 3 edges. So the diameter is 3.
Interactive Visualizer: Heights Bottom-Up
Pick an example or type a tree in level order (use null for missing children), then press Next. Each node shows its height once it is computed, and the final step highlights one longest path.
How We’ll Solve It
- Calculate Height and Track Diameter at Once
- For each node, find the height of its left subtree and right subtree.
- A path that passes through this node has length
leftHeight + rightHeight(in edges). - Keep a global
diametervariable and update it wheneverleftHeight + rightHeightis bigger.
- Recursive Height Function
- Returns the height of the subtree (in nodes).
- While returning, it also updates the diameter.
This way, we only walk the tree once (O(N) time), and we don’t need extra data structures.
Code Implementation
class Solution:
diameter = 0 # holds the maximum diameter found
def calculateHeight(self, root):
# Base case: empty tree has height 0
if not root:
return 0
# Recursively find heights of left and right subtrees
leftHeight = self.calculateHeight(root.left)
rightHeight = self.calculateHeight(root.right)
# Update diameter: path through root uses leftHeight + rightHeight edges
self.diameter = max(self.diameter, leftHeight + rightHeight)
# Return the height of this subtree (in nodes)
return 1 + max(leftHeight, rightHeight)
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
# Initialize diameter and start recursion
self.diameter = 0
self.calculateHeight(root)
return self.diameterclass Solution {
private int diameter = 0; // holds the maximum diameter found
private int calculateHeight(TreeNode root) {
// Base case: empty tree has height 0
if (root == null) return 0;
// Recursively find heights of left and right subtrees
int leftHeight = calculateHeight(root.left);
int rightHeight = calculateHeight(root.right);
// Update diameter: path through root uses leftHeight + rightHeight edges
diameter = Math.max(diameter, leftHeight + rightHeight);
// Return the height of this subtree (in nodes)
return 1 + Math.max(leftHeight, rightHeight);
}
public int diameterOfBinaryTree(TreeNode root) {
// Initialize diameter and start recursion
diameter = 0;
calculateHeight(root);
return diameter;
}
}class Solution {
int diameter = 0; // holds the maximum diameter found
int calculateHeight(TreeNode* root) {
// Base case: empty tree has height 0
if (!root) return 0;
// Recursively find heights of left and right subtrees
int leftHeight = calculateHeight(root->left);
int rightHeight = calculateHeight(root->right);
// Update diameter: path through root uses leftHeight + rightHeight edges
diameter = max(diameter, leftHeight + rightHeight);
// Return the height of this subtree (in nodes)
return 1 + max(leftHeight, rightHeight);
}
public:
int diameterOfBinaryTree(TreeNode* root) {
// Initialize diameter and start recursion
diameter = 0;
calculateHeight(root);
return diameter;
}
};Step-By-Step Explanation
- Global Variable
diameter- We store the largest sum of left and right subtree heights (in edges).
calculateHeight(root)- If
rootisNone, height is 0. - Otherwise:
- Compute
leftHeight = calculateHeight(root.left). - Compute
rightHeight = calculateHeight(root.right). - Update
diameterwithleftHeight + rightHeightif it’s larger. - Return
1 + max(leftHeight, rightHeight)as the subtree height.
- Compute
- If
diameterOfBinaryTree(root)- Reset
diameterto 0. - Call
calculateHeight(root). - Return the final
diameter.
- Reset
This works because every node gets a chance to consider the path that goes through it. The longest such path anywhere in the tree is our answer.
Dry Run on Example
1
/ \
2 3
/ \
4 5calculateHeight(4)→ left and right areNone→ heights 0,0 → diameter = max(0,0) → returns 1calculateHeight(5)→ same → returns 1- At node 2:
- leftHeight=1, rightHeight=1 → diameter = max(0,1+1)=2
- returns 1 + max(1,1)=2
calculateHeight(3)→ returns 1- At node 1:
- leftHeight=2, rightHeight=1 → diameter = max(2,2+1)=3
- returns 1 + max(2,1)=3
Final diameter = 3.
Time & Space Complexity
- Time: O(N) — we visit each node once.
- Space: O(H) — recursion stack up to tree height H (worst-case O(N) for skewed tree, O(log N) for balanced tree).
Frequently Asked Questions
What is the diameter of a binary tree?
It is the number of edges on the longest path between any two nodes in the tree. For the tree [1,2,3,4,5] the diameter is 3, for example the path 4 → 2 → 1 → 3.
Does the diameter always pass through the root?
No. The longest path can sit entirely inside one subtree, which is why the solution checks leftHeight + rightHeight at every node, not only at the root. Try the “Not through root” example in the visualizer.
What is the time and space complexity of the diameter solution?
Each node is visited once, so it runs in O(n) time. The recursion uses O(h) space, where h is the height of the tree: O(log n) for a balanced tree and O(n) for a skewed one.
Why is the naive solution O(n²)?
Computing the height separately for every node visits the same subtrees again and again. The one-pass solution returns the height and updates the diameter in the same call, so each node is processed only once.
What is the difference between height and diameter?
Height is the longest path from a node down to a leaf. Diameter is the longest path between any two nodes, which at its highest point equals the left height plus the right height of some node.
For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.
