Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find Distance Between Two Nodes

Medium Acceptance 62.45% Points 30.00

You are given the root of a binary tree and two node values, n1 and n2. Your task is to find the distance between the two nodes.

The distance between two nodes is defined as the number of edges on the shortest path connecting them. This path passes through their Lowest Common Ancestor (LCA).

Return the distance between n1 and n2.

Examples
Example 1

image Input: root = [1,2,3,4,5,6,7], n1 = 4, n2 = 5
Output: 2
Explanation: The path 4 → 2 → 5 has 2 edges, so the distance is 2.

Example 2

image Input: root = [1,2,3,4,5,6,7], n1 = 4, n2 = 6
Output: 4
Explanation: The path 4 → 2 → 1 → 3 → 6 has 4 edges, so the distance is 4.

Example 3

image Input: root = [1,2,3], n1 = 2, n2 = 2
Output: 0
Explanation: A node has zero distance to itself.

Constraints
    • 1 = Number of nodes = 104
    • -10? = Node.data = 10?
    • Both n1 and n2 exist in the tree
Companies
Samsung PhonePe
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions