Find Distance in a Binary Tree

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree and the values p and q of two nodes in it, return the **distance** between those nodes: the number of edges on the path connecting them. All values in the tree are distinct and both p and q are present. p and q may be equal, in which case the distance is 0.

Examples

Input: root = [10,4,7,1,9,null,3,null,null,8,2], p = 8, q = 3
Output: 5
The path is 8 -> 9 -> 4 -> 10 -> 7 -> 3, which has 5 edges.
Input: root = [10,4,7,1,9,null,3,null,null,8,2], p = 4, q = 2
Output: 2
2 is a grandchild of 4 through 9.
Input: root = [10,4,7,1,9,null,3,null,null,8,2], p = 9, q = 9
Output: 0
A node is at distance 0 from itself.

Constraints

  • 1 <= number of nodes <= 10^4
  • 0 <= Node.val <= 10^9
  • All values are distinct
  • `p` and `q` are values of nodes in the tree

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems