235. Lowest Common Ancestor of a Binary Search Tree
Practice Lowest Common Ancestor of a Binary Search Tree for free on NudgeCode: Medium, Binary Tree pattern. Write it in Python or JavaScript, run the tests in your browser, and ask for a hint when you are stuck.
Given a binary search tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both p and q as descendants (a node counts as a descendant of itself).
In the tests p and q are given by value; all values are unique. The expected output is the value of the node you return.
Example
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 -> 6
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 -> 2
Constraints
- 2 <= number of nodes <= 10^5
rootis a valid BSTpandqare different nodes that exist in the tree