The deepest node both of them are under
MediumStuck?
Show a hintHide the hint
Return the node itself if it is p or q. Otherwise recurse both ways: if both sides come back with something, the paths part here.
The ideas behind this problem
Next in this lesson
How deep does the tree goGiven a binary tree and two values p and q that both appear in it, report the value of their lowest common ancestor: the deepest node that has both of them somewhere beneath it.
A node counts as an ancestor of itself, so if one of them sits above the other, that one is the answer.
Worked example#
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
p = 5,q = 1gives 3, the root, because that is where the two branches part.p = 5,q = 4gives 5, because 4 is beneath 5 and a node is its own ancestor.
The idea#
Every node in the tree is in exactly one of three situations:
- It is
porq. Then it is the deepest thing worth reporting from this subtree, so report it upwards. - It found something on both sides. Then
pcame from one side andqfrom the other, so the paths part here and this node is the answer. - It found something on one side only. Then whatever it found is the best answer so far in this subtree, so pass it up unchanged.
Write that as a recursion and the algorithm is four lines:
walk(node):
if node is nothing, or node is p, or node is q:
return node
left = walk(node.left)
right = walk(node.right)
if both are non-empty: return node # the paths part here
return whichever one is non-empty
The part worth pausing on#
Case 1 returns as soon as it sees p, without checking whether q is beneath it. That looks wrong and is not. If q is beneath p, then p is the answer, and returning p upward gives exactly that. If q is elsewhere, some node higher up will see p from one side and q from the other, and case 2 catches it.
This is one recursion, one pass, no parent pointers and no stored paths.
Constraints#
1 <= number of nodes <= 100000pandqboth appear in the tree, and are different values
About the input#
The tree is written level by level with null for a missing child, the count first, then p, then q.
Input
root is a count then that many tokens level by level. Then p on its own line, then q.
Output
Print the value of the lowest common ancestor.
Examples
Input
9 3 5 1 6 2 0 8 null null 5 1
Output
3
The branches part at the root.
Input
13 3 5 1 6 2 0 8 null null 7 4 null null 5 4
Output
5
4 is beneath 5, and a node is its own ancestor.
Input
3 1 2 3 2 3
Output
1
Two children of the root.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.