Lowest Common Ancestor of a Binary Tree
ID: 88; medium
Solution 1 (Java)
Notes
There are 4 general cases.
If
root
isA
orB
, we directly return the root since bothA
andB
are guaranteed to be in the tree. If theroot
is one of them, then the other one must be its descendent.If
A
andB
are on the different sides of theroot
, then theroot
of the LCA.If
A
andB
are both in the left tree, then we find the LCA of the left tree.If
A
andB
are both in the right tree, then we find the LCA of the right tree.
Last updated