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
Coding & Algorithms
Software Engineer
Salesforce
August 12, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

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
Tree Data Structures
Graph Algorithms
Breadth-First Search (BFS)
Depth-First Search (DFS)
Complexity Analysis
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Approach

To find the diameter of an undirected tree, we can use the following approach:

  1. Perform a BFS (or DFS) from an arbitrary node to find the farthest node from it. Let's call this node A.
  2. 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...

Submit Your Answer
Markdown supported

Related Questions