Diameter of an Undirected Tree
Last updated: August 12, 2026
Quick Overview
The question asks the candidate to determine the diameter of an undirected tree, which is the longest path between any two nodes in the tree.
Salesforce
August 12, 20260
0
13 solved
The question asks the candidate to determine the diameter of an undirected tree, which is the longest path between any two nodes in the tree.
This question is commonly asked during onsite interviews for software engineering roles to evaluate the candidate's understanding of tree data structures and their ability to implement algorithms efficiently. It tests problem-solving skills, coding proficiency, and the ability to write clean and executable code under time constraints.
What the Interviewer Expects
- Explain the concept of tree diameter clearly.
- Describe the approach to finding the diameter using BFS or DFS.
- Provide a clean and executable code solution in Python.
- Discuss the time and space complexity of the solution.
- Mention edge cases and how to handle them.
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Can you explain how you would optimize this solution further?
- What would you do differently if the tree were not undirected?
- How would you handle trees with a large number of nodes?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Approach
To find the diameter of an undirected tree, we can use the following approach:
- Perform a BFS (or DFS) from an arbitrary node to find the farthest node from it. Let's call this node A.
- Then, perf...
Algorithm
Here is the Python code implementing the above approach:
from collections import deque
def bfs(start_node, graph):
visited = set()
queue = deque([(start_node, 0)]) # (node, distanc...