π΅235. Lowest Common Ancestor of a Binary Search Tree
Easy | Grind 75 | August 27 Saturday, 2022
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: βThe lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).β
Constraints:
The number of nodes in the tree is in the range
[2, 105].-109 <= Node.val <= 109All
Node.valare unique.p != qpandqwill exist in the BST.

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant
of itself according to the LCA definition.Input: root = [2,1], p = 2, q = 1
Output: 2SOLUTION
Binary Search Tree VS Binary Tree
Binary TreeA binary tree is a tree data structure whereby ever node has at most 2 node child.Binary Search Tree: is a sorted binary tree. Ever node is bigger than its left subtree but smaller than its right subtree.
We know that if the current node we are looking at is smaller than both p and q, we need to search the right subtree because thats the only place where we can find p and q. Similarly, we only search it's left subtree when the current node is greater than p and q. If the current node is larger than p and smaller than q or vice versa, then the current node is our LCA because this is where the path for p and q diverges. If the current node is either p or q, we directly return the current node.
CODE: the code is exactly as the explanation above. We use recursion to traverse the tree. If the root node is smaller than both p and q, we traverse the tree with root.right as the root. If the root is bigger than both p and q, we traverse the tree with root.left as the root. We repeat this until the path diverges or the root node is equal to p or q.
TIME AND SPACE COMPLEXITY
TIME: O(logn) where n is the number of nodes. Every time we traverse, we either take the left or right subtree. In doing that, we eliminate half of the search space.
SPACE: O(1) we do not store anything.
Last updated