lowest-common-ancestor-of-a-bst.sh — zsh

Lowest Common Ancestor of a BST

medium
binary-treebinary-search-treedepth-first-search

Given a BST and two values present in it, return the value of their lowest common ancestor.

Constraints

  • 2 <= number of nodes <= 10000
  • All node values are unique
  • p and q exist in the tree

Follow-up

How does BST ordering avoid a full tree traversal?

Examples
Example 1
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Example 2
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Example 3
Input: root = [2,1], p = 2, q = 1
Output: 2
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.