Finding the lowest common ancestor a binary search tree (Google interview question)
Hey all! This problem is a commonly asked question at Google, Facebook, and other top tech companies, so I wanted to go over it.
Given a binary search tree (BST), find the lowest common ancestor (LCA) 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).”
You can find the problem here: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

For example, given 2 and 4, the lowest common ancestor is 2.
Given 4 and 7, the lowest common ancestor is 6.
Given 7 and 9, the lowest common ancestor is 8.
Now this problem is a bit easier than if we were given a binary *tree*, instead of a binary *search* tree. Binary *search* trees have a nice property that for a given node, everything to the left of the node is smaller than the given node’s value, and everything to the right is greater than it. Let’s take advantage of that property. But first…
Tree problems, recursion. Tree problems, recursion. Tree problems, recursion. Get that in your head!!!
Let’s think about what we would want to do given any node.
1/ If p and q are smaller than the given node’s value, we know the ancestor must be to the left.
2/ If p and q are both larger than the given node’s value, we know the ancestor must be to the right.
3/ Else, meaning the p < node’s value < q, or p is the node or q is the node, we just return the node.

Let me know if you have any questions or if there’s another problem you want me to solve!
For more articles like this, follow me on Medium. Not a member yet? Join the community. Want more software engineering interview guides and coding question tips? Check out all of my writing organized by topic in this article.
If you have any requests for what I should write, please let me know!






