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

          6
        /   \
      11     2
     /  \     \
    4    9     13
        / \   /
       1   7 5

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

Input:  root = build_tree([6, 11, 2, 4, 9, None, 13, None, None, 1, 7, 5]), p = 11, q = 1
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…