Quick revision
The short answer
The lowest common ancestor of two nodes is found with tree recursion where each subtree reports what it found. A call returns p or q if it stands on one of them; otherwise it asks both children, returns itself if both sides found something, and passes up whatever one side found. One post-order pass takes O(n) time and O(h) space for the recursion, where h is the height of the tree.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Top-down: search each side at every level (brute force) | O(n h), O(n^2) for a chain | O(h) |
| Find both root paths, then compare them | O(n), two searches | O(h) for two paths |
| One post-order pass, subtrees report up | O(n) | O(h) call stack |
What to remember
We found the lowest common ancestor by letting every subtree report once what it contains: null for nothing, p or q for one target, or the answer for both. The first node that hears from both sides is where the paths split, and every node above it passes the answer up. That is O(n) time and O(h) space, where the top-down search repeated work and cost O(n h). The clue to remember is a question about what lies below a node: build the answer from what the left and right subtrees report, in one post-order pass.
1What the lowest common ancestor is, seen in a family tree
Think of a family tree drawn with the oldest person at the top. You and a cousin both have grandparents and great-grandparents in common. Both are your common ancestors, but the grandparent is lower in the drawing, closer to you both. That nearest shared relative is what this problem calls the lowest common ancestor. Lowest means deepest in the drawing, the one furthest from the top.
A binary tree is drawn the same way. The top node is the root, and each node has at most two children, a left child and a right child. An ancestor of a node is any node on the path from the root down to it, and by the usual convention a node counts as its own ancestor. We are given the root and two nodes, called p and q, and must return the deepest node that is an ancestor of both. This problem is smaller than it looks, because the answer is simply the place where the paths from the root to p and to q go separate ways.
Our example tree has root 1 with children 2 and 3. Node 2 has children 4 and 5, node 3 has children 6 and 9, and node 5 has children 7 and 8. Take p = 4 and q = 8 and work it by hand. The path from the root to 4 is 1, 2, 4. The path to 8 is 1, 2, 5, 8. Walking down both together, they share 1, then share 2, and then one goes to 4 while the other goes to 5. The last shared node is 2, so the answer is 2.
The two nodes we are asked about are marked, and so is their lowest common ancestor. Node 1 is also a common ancestor, but a higher one.
- path to p
- 1 -> 2 -> 4
- path to q
- 1 -> 2 -> 5 -> 8
- shared
- 1 and 2
- lowest shared
- 2
1The path from the root to 4 is 1, 2, 4 and the path to 8 is 1, 2, 5, 8. They share 1 and 2, and the deeper of those, node 2, is the answer.
What to assume
- Is it a binary search tree, where smaller values sit on the left?
- No, it is a general binary tree, so values give no hint about direction.
- Are p and q given as node references, and are both surely in the tree?
- We assume so.
- Does each node know its parent?
- No, we can only walk downwards.
Try a few more on paper. For 7 and 8 the paths split right after 5, so the answer is 5, their parent. For 8 and 6 they split at the root, so the answer is 1. For 2 and 7 the path to 7 passes through 2 itself, so 2 is the answer, because a node counts as its own ancestor.
A careful candidate asks some questions first. Is it a binary search tree, where smaller values sit on the left? No, it is a general binary tree, so values give no hint about direction. Are p and q given as node references, and are both surely in the tree? We assume so and handle a missing node in the follow-ups. Does each node know its parent? No, we can only walk downwards.
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 a tree problem solved by reports from below
A beginner's first instinct is to do exactly what we did by hand: find the path to p, find the path to q, and compare them. That is a sound instinct, and it already shows the key fact, that the answer is where the paths split. The question is how to find that split point without walking the tree several times.
The first clue is the word tree together with the word ancestor. Ancestor is a question about what lies below a node. A node is a common ancestor exactly when its subtree, meaning the node together with everything hanging below it, contains both p and q. So the question at every node is the same small question: what does my subtree contain?
The second clue is that a node's subtree is just the node plus its left subtree plus its right subtree. If the left child could tell us what it found, and the right child could too, the node could answer for itself without looking any deeper. When the answer at a node can be built from answers about its two subtrees, recursion is the natural tool: a function that calls itself on the children and combines what they return.
These clues point to the trees pattern in its most common form, recursion where each subtree reports up. Because each node waits until both children have reported before combining, the nodes finish in post-order, which means children first, then the parent. The general rule to carry to new problems is to ask, at a single node, what one small report from each child would let this node answer its own question, and to make the recursive function return exactly that report. Height, balance, diameter and path sums all follow this rule.
Two look-alikes need care. In a binary search tree we could walk down by comparing values, and with parent links we could walk up from p and q like two linked lists meeting. Neither is given here, so we need the general method.
3The honest first attempt, asking which side each node is on
The first attempt most people write copies the hand method from the top. Stand on the root and ask two questions: is p somewhere in the left subtree, and is q? If both are on the left, step left; if neither is, both must be on the right, so step right; if they are on different sides, we are standing exactly where the paths split, so this node is the answer. If we stand on p or q itself, that node is the answer too. This brute force is correct and easy to explain, which makes it a good start.
Let us count on the example with p = 4 and q = 8. At the root, contains searches 2's subtree for 4 and visits two nodes, then searches it again for 8 and visits five. Both are on the left, so we step to 2. There we search 4's subtree for 4 and for 8, one visit each, find them on different sides, and return 2. That is nine visits for a nine node tree, which looks harmless.
The waste shows on a different shape. Take a chain of eight nodes, each the left child of the one above, and ask for the two deepest. At the first node, the searches walk nearly the whole chain twice. At the next, they walk nearly all of it twice again. The program reports 48 node visits for a tree of 8 nodes. In general each level searches up to n nodes and there are up to h levels, so the time is O(n times h), which is O(n squared) for a chain.
So where exactly is the waste? When we step down from a node to its child, we search the child's subtree again, although the search one level up already walked every node in it. The information was found and thrown away. The question that leads further is this: could each node be visited once and tell its parent what it saw?
4Turning the question around so every subtree reports upwards
Instead of a parent asking each subtree whether it contains p, then whether it contains q, again and again, let every subtree answer once, from the bottom up, with the one thing its parent needs. Think of the family tree again: instead of the oldest ancestor sending a messenger down every branch twice, each family reports up to its parent which of the two people it has seen.
So we define lca(node) to return one of four things. It returns null if the subtree contains neither p nor q. It returns p or q if the subtree contains just that one. And it returns the answer if the subtree contains both. Notice that the third and fourth cases both return a node, which seems confusing at first; we will see in a moment why the parent never needs to tell them apart.
Now the function almost writes itself. If the node is null, an empty spot, report null. If the node is p or q, report the node itself. Here a beginner asks a fair question: why stop, when the other target might be below? Because if it is below, this node is still the answer, being its own ancestor and an ancestor of the other one. And if the other target is elsewhere, the parent needs only to hear that this one was found.
Otherwise we ask the left child and the right child and look at their two reports. If both are non-null, one side holds p and the other holds q, so this node is exactly where the paths split: report this node. If only one side is non-null, pass that report up unchanged. If both are null, report null. That is the whole algorithm.
Why is the node it returns the lowest common ancestor and not just any common ancestor? Going upwards, the first node that hears something from both sides is the first node whose subtree holds both p and q, which makes it the deepest such node. Every node above it hears something from one side only, so it passes the answer up untouched, and this is why the parent never needs to know whether a report is a target or the final answer. A tempting mistake is to return true or false instead of a node. A yes or no tells the parent that something was found, but loses which node it was, and the answer is a node.
5Watching every report on the example
The picture follows lca(root, 4, 8) call by call. The label call marks the node we are visiting, and the panel shows the call stack, which is the list of calls still waiting for an answer, along with the two reports this call received and what it reports upwards.
Watch the order in which nodes finish. A node is only decided after both of its children have reported, except when it is p or q, which decides at once.
The label call sits beside the node whose call we are in. Nodes that reported null are marked finished, nodes that reported p or q are marked compared, and the node that found both is marked found.
- call stack
- 1
- this call
- lca(1)
- left report
- -
- right report
- -
- reports
- deciding
1
lca(1)starts at the root. Node 1 is neither 4 nor 8, so before deciding anything it asks its left subtree, rooted at 2.- call stack
- 1, 2
- this call
- lca(2)
- left report
- -
- right report
- -
- reports
- deciding
2
lca(2)is also neither target, so it too asks its left child first. Two calls are now waiting on the stack, for 1 and for 2.- call stack
- 1, 2, 4
- this call
- lca(4)
- left report
- not asked
- right report
- not asked
- reports
- 4
3
lca(4)finds that node 4 is p itself, so it reports 4 at once without looking below it.- call stack
- 1, 2, 5, 7
- this call
- lca(7)
- left report
- null
- right report
- null
- reports
- null
4Back at 2, the right child 5 is asked, and 5 asks 7. Both of 7's children are empty, so
lca(7)reports null: nothing here.- call stack
- 1, 2, 5, 8
- this call
- lca(8)
- left report
- not asked
- right report
- not asked
- reports
- 8
5
lca(8)finds that node 8 is q, so it reports 8 straight away.- call stack
- 1, 2, 5
- this call
- lca(5)
- left report
- null
- right report
- 8
- reports
- 8
6Node 5 heard null from the left and 8 from the right. Only one side found something, so 5 passes the 8 up unchanged.
- call stack
- 1, 2
- this call
- lca(2)
- left report
- 4
- right report
- 8
- reports
- 2
7Node 2 heard 4 from the left and 8 from the right. Both sides found something, so p and q split here, and 2 reports itself.
- call stack
- 1, 3, 6
- this call
- lca(6)
- left report
- null
- right report
- null
- reports
- null
8Back at the root, the right subtree is asked next.
lca(3)asks 6, whose children are empty, so 6 reports null.- call stack
- 1, 3, 9
- this call
- lca(9)
- left report
- null
- right report
- null
- reports
- null
9
lca(9)also has no children and is not a target, so it reports null as well.- call stack
- 1, 3
- this call
- lca(3)
- left report
- null
- right report
- null
- reports
- null
10Node 3 heard null from both sides, so its whole subtree contains neither node, and it reports null to the root.
- call stack
- 1
- this call
- lca(1)
- left report
- 2
- right report
- null
- reports
- 2
11The root heard 2 from the left and null from the right. Only one side found something, so it passes 2 up. The answer is 2.
Let us read the key frames back. In the third frame node 4 reports itself without looking below, the early stop we discussed. In the sixth, node 5 hears null and 8 and simply passes the 8 along, still waiting for a partner. In the seventh, node 2 hears 4 from one side and 8 from the other, the first node to hear from both, so it reports itself.
The last four frames are worth noticing too. The recursion still searches the whole right subtree under 3, because the root cannot know in advance that nothing is there. That costs a few visits but keeps the code simple, and the total is still one visit per node. At the root only one side reported something, so the answer 2 passes through unchanged.
6The complete Java program
Here is the full program. main builds the example tree and asks five questions: our example, two siblings, nodes on opposite sides of the root, a node together with its own descendant, and a node asked about itself.
Let us read lca in the order it runs. The first line handles three situations at once. If root is null, we have stepped past a leaf, and null means found nothing. If root is p or q, we report it, as we reasoned. Comparing with == checks that it is the very same node object, not just the same value, so trees with repeated values still work.
Next come the two recursive calls. Java finishes the whole left call, with all the calls it makes in turn, before it starts the right call. That is why the picture walked down the left side completely before touching node 3. Each call's result is kept in left and right, the two reports.
The last two lines combine the reports. If both are non-null, p and q are on different sides, so root is the split point and we return it. Otherwise we return whichever report is non-null, or null if both are. The expression left != null ? left : right reads as: if left found something, pass it up, otherwise pass up whatever right has, which may be null.
So main prints 2 for 4 and 8, 5 for the siblings 7 and 8, 1 for 8 and 6, and 2 for 2 and 7, since the call stops at 2 without ever looking for 7. The last line asks about node 4 alone, starting from 4, and gets 4.
7How much it costs, and the cases at the edges
Let us count on the example first. Every one of the nine nodes was entered at most once, and each did a constant amount of work after its children reported, so the time is O(n). On the eight node chain where the top-down search made 48 visits, this version makes at most 8. We cannot do better in general, because without any order in the values, p or q could be hiding in any node we skip.
The extra space is the call stack. At the deepest moment of our example, the calls for 1, 2, 5 and 7 were waiting together, four calls for a tree of height four. In general the space is O(h), where h is the height: about log n for a well balanced tree and up to n for a chain.
| Approach | Time | Extra space |
|---|---|---|
| Top-down: search each side at every level (brute force) | O(n h), O(n^2) for a chain | O(h) |
| Find both root paths, then compare them | O(n), two searches | O(h) for two paths |
| One post-order pass, subtrees report up | O(n) | O(h) call stack |
The edge cases need little code. When one node is an ancestor of the other, as with 2 and 7, the search stops at 2 and returns it, correct under the convention. When p and q are the same node, it is returned. An empty tree returns null.
The one assumption to say aloud is that both nodes are in the tree. If q were missing, the search would still return p, which is wrong, and the first follow-up below fixes that. For a very deep tree, where recursion could overflow the stack, an iterative version that records each node's parent in a HashMap avoids recursion.
8Follow-up questions
What if p or q might not be in the tree?
Then the early stop is no longer safe, because finding p alone would still be reported as an answer. The fix is to keep searching the whole tree and count how many of the two targets were actually seen, for example with two boolean flags set when the traversal meets p and when it meets q. The recursion combines reports exactly as before, but at the end we return the result only if both flags are true, and null otherwise. It stays O(n) time and O(h) space.
How does the answer change if the tree is a binary search tree?
In a binary search tree every value on the left of a node is smaller and every value on the right is larger, so the values tell us which way to go. Starting at the root, if both p and q are smaller than the node, we move left; if both are larger, we move right; otherwise they split here, or one of them is this node, and we return it. That is a single walk down, O(h) time, and it can be a plain loop with O(1) space.
Can you solve it without recursion?
Yes. We walk the tree with our own stack or a queue and record each node's parent in a HashMap until both p and q have been seen. Then we walk up from p to the root, putting every ancestor into a HashSet, and walk up from q until we meet a node already in the set. That first shared node is the answer. It is O(n) time and O(n) space, and it cannot overflow the call stack on a very deep tree.
9Conclusion
We found the lowest common ancestor by letting every subtree report once what it contains: null for nothing, p or q for one target, or the answer for both. The first node that hears from both sides is where the paths split, and every node above it passes the answer up. That is O(n) time and O(h) space, where the top-down search repeated work and cost O(n h). The clue to remember is a question about what lies below a node: build the answer from what the left and right subtrees report, in one post-order pass.
Open with
Let me check the assumptions: it is a general binary tree, not a search tree, I get node references, both nodes are in the tree, and a node counts as its own ancestor.
Then, if they want more
Walking down from the root and searching each side for p and q works, but it searches the same subtrees again at every level, so it is O(n times h), quadratic for a chain. Since an ancestor question is about what a subtree contains, I let each subtree report up in one post-order pass.
My function returns null if the subtree has neither node, p or q if it has one, and the lowest common ancestor if it has both. If the current node is null, p or q, I return it straight away. Otherwise I recurse left and right.
If both reports are non-null, p and q split here, so I return the current node. If only one is, I pass it up. The first node that hears from both sides is the deepest one whose subtree holds both, so it is the answer, and nodes above simply pass it along.
Each node is visited once, so it is O(n) time and O(h) space for the recursion. If a node might be missing, I would count how many targets I actually saw before trusting the answer.
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 46 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 tree.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-lowest-common-ancestor-of-two-nodes-in-a-binary-tree-43ab4b/