Problem 459773 · medium · Level 04 Non-Linear Data Structures

Edge Distance Between Two Values

binary tree · lowest common ancestor · recursion

A tree holds distinct integers. Given two values p and q that both occur in the tree, return the number of edges on the path that connects them (0 if p == q).

Examples

          3
        /   \
       5     1
      / \   / \
     6   2 0   8
        / \
       7   4

Input:  root = build_tree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4]), p = 4, q = 0
Output: 5
Explanation: 4 -> 2 -> 5 -> 3 -> 1 -> 0.

Input:  root = build_tree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4]), p = 5, q = 4
Output: 2

Constraints

  • 1 <= number of nodes <= 1000
  • All values are distinct; p and q are present in the tree

Goals

  • Combine the lowest common ancestor with depth measurements
  • Search for a value inside a subtree and return its depth relative to that subtree
Starting Python…