Dsa
Trees
Medium
Diameter of a Binary Tree
Calculate the diameter of a binary tree. The diameter is defined as the length of the longest path between any two nodes in the tree.
Input:
- The first line contains an integer n, representing the number of nodes in the tree.
- The next n lines describe the tree in the format 'parent child direction', where direction can be 'L' (left) or 'R' (right).
Output:
- An integer representing the diameter of the tree.
Example Input:
7
1 2 L
1 3 R
2 4 L
2 5 R
3 6 L
3 7 R
Example Output:
4
Key concepts
treesdiameterdepth-first search
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