Dsa
Trees
Medium
Binary Tree Diameter
The diameter of a binary tree is the length of the longest path between any two nodes in the tree. The path may or may not pass through the root. Write a function that computes the diameter of the binary tree.
Input Format:
- The first line contains an integer n (the number of nodes).
- The next n lines each contain an integer value representing the node value of the binary tree in level order, with -1 indicating a null node.
Output Format:
- Print the diameter of the binary tree as a single integer.
Example:
Input:
7
1
2
3
4
-1
5
6
Output:
4
Key concepts
treesdiameterdepth
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now