Quick revision
The short answer
Finding the lowest common ancestor in a binary search tree uses the BST ordering. We walk down from the root, moving left while both values are smaller than the node and right while both are larger, and return the first node where they split or one of them is the node. It takes O(h) time for a tree of height h and O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space | Uses the BST order? |
|---|---|---|---|
| Record both root paths and compare | O(n) | O(h) | no |
| General binary tree recursion | O(n) | O(h) call stack | no |
| Recursive walk down to the split | O(h) | O(h) call stack | yes |
| Loop walking down to the split | O(h) | O(1) | yes |
What to remember
We found the lowest common ancestor in a binary search tree by walking down from the root once. While both values are smaller than the node we move left, while both are larger we move right, and the first node where they split, or where one of them is the node, is the answer. It costs O(h) time and O(1) space. The clue to remember is the phrase binary search tree: ask what the ordering lets you skip, and walk a single path instead of searching the whole tree.
1What the lowest common ancestor means in a search tree
Think of a family tree drawn on a large sheet of paper, with the oldest grandparent at the top and each generation below. Pick two cousins near the bottom. If you trace each cousin upward, parent by parent, the two lines eventually meet at someone they both descend from. The nearest such person, the one lowest down on the sheet, is the person this question is about. For a parent and their own child, it is the parent, because we count each person as part of their own line.
Trees in programming are drawn the same way, upside down from real trees. The top node is called the root, and each node can have a left child and a right child below it. A node's ancestors are the nodes on the path from the root down to it, and by agreement a node counts as its own ancestor. The lowest common ancestor of two nodes, often shortened to LCA, is the deepest node that is an ancestor of both, which is exactly the nearest shared relative in the family tree.
The question adds one more word, and it makes the problem much easier than it looks. The tree is a binary search tree, or BST. That means it keeps an ordering rule at every node, which is that every value in a node's left subtree, the left child and everything below it, is smaller than the node, and every value in its right subtree is larger. Our example has root 20 with children 8 and 22, then 8 has children 4 and 12, and 12 has children 10 and 14. Check the rule at 8. On its left, 4 is smaller, and on its right, 12, 10 and 14 are all larger.
Smaller values are always on the left of a node and larger values on the right. The LCA of 10 and 14 is marked.
1In this tree the lowest common ancestor of 10 and 14 is 12, their parent, because both of their upward paths first meet at 12.
What to assume
- Are both values guaranteed to be in the tree?
- We assume yes. We also assume the values are distinct, that we receive two values p and q and return the LCA node, and that if p equals q the answer is that node.
Let us find a few answers by hand. Tracing upward, 10 goes to 12, 8 and 20, and 14 goes to 12, 8 and 20, so their lines meet first at 12. For 4 and 14, the line from 4 goes to 8 and 20, and the line from 14 goes to 12, 8 and 20, so they meet first at 8. For 14 and 8, the line from 14 passes through 8, and 8 counts as its own ancestor, so the answer is 8 itself. For 10 and 22, the lines meet only at the root, 20.
A careful candidate asks a few questions first. Are both values guaranteed to be in the tree? We assume yes and return to this at the end. We also assume the values are distinct, that we receive two values p and q and return the LCA node, and that if p equals q the answer is that node.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise when the search tree ordering does the work
A beginner reading this question often thinks first of the family tree method, tracing both nodes and seeing where their lines meet. It is sound, and we will try it next. But in a program a node usually knows only its children, not its parent, so we cannot climb upward. We can only walk down from the root. The question is how to walk down cleverly.
So let us read the question slowly and take its clues one at a time. The first clue is the phrase lowest common ancestor. Every ancestor of a node lies on its path from the root. So the common ancestors of two nodes are the nodes their two root paths share, and they always form the top part of both paths, ending where the paths part. The LCA is the last node before they part.
The second clue is the phrase binary search tree. The ordering rule means that comparing a value with a node tells us which side the value must be on, the same way comparing with the middle of a sorted array tells binary search which half to keep. At 20, the value 10 must be on the left, because everything on the right is larger than 20. We never need to look on the right for it.
Put the two clues together and we reach the binary search trees pattern. Its general rule is this. When a tree question says the tree is a BST, ask what the ordering lets you skip, because a comparison at a node usually rules out a whole subtree, and the answer can be found by walking one path down instead of visiting every node. Such a path is as long as the tree is tall, which for a well balanced tree of a million nodes is only about twenty nodes.
Some patterns look similar but do not fit as well. The general binary tree LCA, a recursive search that asks each subtree whether it contains p or q, also works here, but it may visit every node and ignores the ordering. Breadth-first search, which visits a tree level by level, does not fit, because the answer is about paths.
3The honest brute force, recording both root paths
The honest first attempt is a brute force that copies the family tree method. Since we cannot climb up, we walk down instead. We find the path from the root to p and the path from the root to q, each as a list of nodes, then walk both lists together from the start while they hold the same node. The last node they share is the LCA. It works on any binary tree, a reasonable place to start.
Compared nodes were visited and turned out to be dead ends. Done nodes are on the path being recorded.
- path to 10
- 20, 8, 12, 10
- visits
- 5
1Searching for 10, the path method visits 20, 8 and then 4, a dead end it backs out of, before 12 and 10. The path is 20, 8, 12, 10.
- path to 14
- 20, 8, 12, 14
- visits
- 6
2Searching for 14, it visits 4 again and also 10, both useless, before reaching 14. The path is 20, 8, 12, 14.
- path to 10
- 20, 8, 12, 10
- path to 14
- 20, 8, 12, 14
- answer
- 12
3The two paths agree on 20, 8 and 12 and then part, so the last shared node, 12, is the answer, after eleven visits in all.
The path method tries the left subtree first, then the right. It adds each node to the list as it arrives, and if the target is not found below a node, it removes that node again, a step called backtracking. Let us run it for 10 and 14, as the picture shows. Searching for 10 it visits 20, 8, then 4, a dead end it must back out of, then 12 and 10, five visits. The path is 20, 8, 12, 10. Searching for 14 it visits 20, 8, 4, 12, 10 and 14, six visits, for the path 20, 8, 12, 14. Walking the two lists together, they agree on 20, 8 and 12 and differ next, so the answer is 12.
Now let us count. Each path search can visit every node in the worst case, so with n nodes the time is O(n). The two lists and the waiting recursive calls each hold up to h nodes, where h is the height of the tree, so the space is O(h). For a balanced tree of a million nodes, that can mean a million visits for an answer about twenty levels down.
So where is the waste? Look at node 4 in the picture. Both searches stepped into it, and the search for 14 stepped into 10 as well. Neither visit could ever have helped. 14 is larger than 8, so the ordering rule says it can only be in 8's right subtree, yet the search looked left first. The path method does not know the tree is sorted, so it wanders into subtrees the ordering has already ruled out.
4Getting to a single walk down, one observation at a time
The waste tells us what to fix. We should never step into a subtree that the ordering has ruled out. So let us walk down from the root once, for both values at the same time, and at each node ask where p and q must be. Stand at a node with value v. There are only three possibilities.
If p and q are both smaller than v, both must live in the left subtree, so their two paths both continue to the left, and the place where the paths part is somewhere down there. We move left. If both are larger than v, we move right for the same reason. In the family tree, both cousins belong to the same branch, so their nearest shared relative is in that branch too.
The third possibility is everything else, one value smaller than v and the other larger, or one of them equal to v. Then we stop and return the current node. Here a beginner usually asks a fair question. How can we be sure this is the lowest common ancestor, and not just some common ancestor? Could a node further down be an ancestor of both? Let us test it at 12 with p = 10 and q = 14. 10 is smaller than 12, so it is in 12's left subtree, and 14 is larger, so it is in the right subtree. Any node below 12 lies entirely on one side, so it cannot be above both. And 12 is an ancestor of both, because we only ever moved towards the side containing both values. So 12 is the deepest common ancestor.
A second question follows from it. What if one value equals the node, as with 14 and 8 when we stand at 8? 8 is p itself, so it is its own ancestor, and it is also an ancestor of 14, because we arrived at 8 by following the side that holds 14. Nothing below 8 can be an ancestor of 8 itself, so 8 is the answer. The code handles this case without a special line, because it only moves while both values are strictly smaller or strictly larger.
So the whole method is a loop that moves one step down per pass and stops at the split. It never searches for p or q themselves and needs no recursion and no lists.
5Watching the walk stop at the split
The picture plays the loop on four queries, exactly as the Java code runs them. The current node is highlighted, the two values we are looking for are marked as compared, and nodes we passed through on the way down are shown as finished. No query visits a node off its own path.
Each query starts at the root and moves left or right until p and q are no longer on the same side.
- p, q
- 10, 14
- node
- 20
- decision
- both smaller, go left
1For 10 and 14 we start at the root, 20. Both values are smaller than 20, so both must be in the left subtree and we move left.
- p, q
- 10, 14
- node
- 8
- decision
- both larger, go right
2At 8, both 10 and 14 are larger than 8, so both are in the right subtree and we move right.
- p, q
- 10, 14
- node
- 12
- decision
- split, return 12
3At 12, 10 is smaller and 14 is larger, so they split here. We return 12 after visiting only three nodes.
- p, q
- 4, 14
- node
- 20
- decision
- both smaller, go left
4For 4 and 14 we start again at 20. Both values are smaller than 20, so we move left.
- p, q
- 4, 14
- node
- 8
- decision
- split, return 8
5At 8, 4 is smaller and 14 is larger, so they split at 8 and we return 8.
- p, q
- 14, 8
- node
- 20
- decision
- both smaller, go left
6For 14 and 8 we start at 20. Both are smaller than 20, so we move left.
- p, q
- 14, 8
- node
- 8
- decision
- one equals node, return 8
7At 8, q equals the node. Neither test for strictly smaller or strictly larger passes, so we return 8, its own ancestor.
- p, q
- 10, 22
- node
- 20
- decision
- split, return 20
8For 10 and 22 the root already splits them, 10 smaller and 22 larger, so we return 20 at once.
Let us read the important frames back. The first three frames are our main example. The loop visits 20, 8 and 12, three nodes, where the path method made eleven visits. At 20 both values are smaller, at 8 both are larger, and at 12 they finally disagree.
The seventh frame is the one beginners worry about. At 8, q is 8 itself. The test p < 8 and q < 8 fails, because 8 is not smaller than 8, and the test p > 8 and q > 8 fails too, so the loop falls through to return 8. The last frame shows that the answer can be the root, when the two values sit on opposite sides from the very start.
6The complete Java program
Here is the complete program. The Node is a Java record, a short way of declaring a class whose fields are fixed when the object is made, here a value and two children. The extra constructor makes a leaf. main builds our example tree and runs five queries, including p equal to q.
Let us read lca in the order it runs. node starts at the root. The while loop runs as long as node is not null, so an empty tree skips the loop entirely. Inside, the first test asks whether both p and q are smaller than node.val(). If so, the split must be on the left, and node = node.left() takes one step down. The second test asks the mirror question, and node = node.right() steps right. A record provides val(), left() and right() as methods, hence the brackets.
If neither test passes, the values do not lie on the same side, or one of them is this node, and we return node at once. The last line, return null, is reached only when the tree is empty, because with both values present the loop always finds the split before it runs off the bottom.
The mistake beginners make most often here is to test only one value, for example moving left whenever p is smaller than the node. Try it with p = 10 and q = 22 at the root. 10 is smaller, so we would move to 8 and lose 22 for good, returning a node that is not an ancestor of 22 at all. Both values must agree before we move. Using less than or equal in the tests is a second slip, because it walks past a node equal to p or q.
In main, the first four queries print the answers we found by hand, and lca(root, 4, 4) prints 4, because when p equals q both tests fail at 4. The order of p and q never matters, since the tests treat them alike.
7How much it costs, and the cases at the edges
Let us count on the example first. The query for 10 and 14 visited three nodes, one per level from the root down to 12. In general the loop moves one level down per pass, so it makes at most h + 1 passes, where h is the height of the tree. The time is O(h). In a balanced BST, h is about log n, the number of times n can be halved, so a million nodes need about twenty steps. In a badly unbalanced BST, one that is really a chain, h can be n, and the time is O(n). The extra space is the single variable node, so O(1).
| Approach | Time | Extra space | Uses the BST order? |
|---|---|---|---|
| Record both root paths and compare | O(n) | O(h) | no |
| General binary tree recursion | O(n) | O(h) call stack | no |
| Recursive walk down to the split | O(h) | O(h) call stack | yes |
| Loop walking down to the split | O(h) | O(1) | yes |
Now the edge cases. An empty tree returns null. When p equals q, the loop walks down to that node and returns it. When one value is an ancestor of the other, as with 14 and 8, the ancestor is returned. When the values sit on opposite sides of the root, the root is returned at once.
One case needs a promise. The loop assumes both values are in the tree, and never checks. If we asked for 10 and 99, the loop would stop at 20, because 10 is smaller and 99 larger, and return 20 although 99 is nowhere in the tree. Without that promise, we first look each value up with an ordinary BST search, also O(h), and return null if either is missing.
8Follow-up questions
How would you find the LCA in a binary tree that is not a search tree?
Without the ordering we cannot tell which side a value is on, so we ask each subtree. A recursive method returns the node itself if it is p or q, and otherwise asks its left and right children. If both children report finding something, p and q are on different sides, so this node is the LCA. If only one side reports something, we pass that result upward. It visits each node at most once, so it is O(n) time and O(h) space for the recursion.
Can you write the BST walk recursively?
Yes. If both values are smaller than the root's value, return the result of calling the method on the left child. If both are larger, call it on the right child. Otherwise return the root. It makes exactly the same decisions as the loop, but every step down waits on the call stack, so it uses O(h) space. The loop is just as short and uses O(1), so it is usually the better answer.
How would you find the distance between two nodes in a BST?
First find their LCA with the same walk. Then the path from one node to the other goes up to the LCA and down again, so the distance is the depth of p below the LCA plus the depth of q below it. Each depth is found with an ordinary BST search from the LCA that counts its steps. Three walks of at most h steps each keep the whole thing O(h).
9Conclusion
We found the lowest common ancestor in a binary search tree by walking down from the root once. While both values are smaller than the node we move left, while both are larger we move right, and the first node where they split, or where one of them is the node, is the answer. It costs O(h) time and O(1) space. The clue to remember is the phrase binary search tree: ask what the ordering lets you skip, and walk a single path instead of searching the whole tree.
Open with
Let me confirm the setup. The tree is a binary search tree with distinct values, I get two values p and q that are both in the tree, a node counts as its own ancestor, and I return the LCA node.
Then, if they want more
A general approach is to record the root-to-node path for each value and take the last node the paths share, but that can visit every node, so it is O(n), and it ignores the ordering. In a BST, comparing a value with a node tells me which subtree it is in. So I walk down from the root.
If both p and q are smaller than the current value, the LCA is in the left subtree, so I go left. If both are larger, I go right. Otherwise they split at this node, or one of them is this node, and I return it.
No node below the split can be an ancestor of both, because each lies on one side, so this is the lowest one. The loop moves one level per step, so it is O(h) time, which is O(log n) for a balanced tree, and O(1) space.
If the values might be missing, I would verify each with a BST search first.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 16 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the lowest common ancestor of two nodes in a binary search tree.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-lowest-common-ancestor-of-two-nodes-in-a-binary-search-9491aa/