Talentd
FleetCode

1740. Find Distance in a Binary Tree

Medium74.3% acceptance2 companiesPremium elsewhere, free here

Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.

The distance between two nodes is the number of edges on the path from one to the other.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
Output: 3
Explanation: There are 3 edges between 5 and 0: 5-3-1-0.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
Output: 2
Explanation: There are 2 edges between 5 and 7: 5-2-7.

Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
Output: 0
Explanation: The distance between a node and itself is 0.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 109
  • All Node.val are unique.
  • p and q are values in the tree.

Asked at 2 companies

Hints open one at a time

Hint 1
Get the LCA of p and q.
Hint 2
The answer is the sum of distances between p-LCA and q-LCA
11:47
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[3,5,1,6,2,0,8,null,null,7,4]
5
0
Input
[3,5,1,6,2,0,8,null,null,7,4]
5
7
Input
[3,5,1,6,2,0,8,null,null,7,4]
5
5
Your code is saved on this device.Solution