Find shortest distance in binary tree

Last updated: November 7, 2025

Quick Overview

Given a binary tree and two nodes, find the shortest distance between the two nodes in the tree. The distance is defined as the number of edges in the path connecting the two nodes. You may assume that both nodes exist in the tree.

Salesforce
Coding & Algorithms
Software Engineer
Salesforce
November 7, 2025
Software Engineer
Onsite
Coding & Algorithms
Hard

4

11

3,088 solved


Given a binary tree and two nodes, find the shortest distance between the two nodes in the tree. The distance is defined as the number of edges in the path connecting the two nodes. You may assume that both nodes exist in the tree.

This coding problem is frequently asked during Onsite at Salesforce. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Salesforce expects candidates to write production-quality code, not just solve the puzzle.

What the Interviewer Expects
  • Quickly identify the optimal approach and its theoretical basis
  • Handle complex algorithm design with multiple interacting components
  • Write concise, elegant code under time pressure
  • Prove correctness of your approach and discuss alternative solutions
  • Optimize beyond the obvious: discuss constant factor improvements
  • Address follow-up variations and explain how the solution generalizes
Key Topics to Cover
Data structure selection and trade-offs
Time and space complexity analysis
Hash maps and frequency counting
Binary search and divide and conquer
Sorting and searching
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 solve this iteratively instead of recursively (or vice versa)?
  • Can you solve this in a single pass?
  • How would you parallelize this solution?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

To find the shortest distance between two nodes in a binary tree, we can use the concept of the Lowest Common Ancestor (LCA). The shortest path between two nodes in a tree can be defined as the path f...

Approach
  1. Find the LCA: Use a recursive function to determine the LCA of the two nodes. The function checks if the current node is one of the nodes we're looking for. If we find one node in the left subt...

Submit Your Answer
Markdown supported

Related Questions