Distance Between Two Nodes Problem

Vivek Srivastava
Techie Delight
Nov 11, 2023

--

Given the root of a binary tree and two tree nodes, x and y, return the distance between x and y in the binary tree. The distance between two nodes is defined as the total number of edges in the shortest path from one node to other.

For example, consider the following binary tree.

Input: x = Node 7, y = Node 6
Output: 3

Input: x = Node 4, y = Node 8
Output: 5

Input: x = Node 5, y = Node 5
Output: 0

Note: The solution should return a negative value if either x or y is not the actual node in the tree.

Practice link: https://www.techiedelight.com/?problem=DistanceBetweenTwoNodes

--

--