Lowest Common Ancestor III
ID: 578; medium
Solution 1 (Java)
Notes
We use the
Result
class to keep track of the status ofA
andB
in the tree.If
a
andb
are bothtrue
, which means the currentroot
is already is LCA, then we setres
only when it is null. This if statement istrue
for the LCA and its ancestors, but we are guaranteed to have the LCA. The reason is that we are doing a DFS and the LCA appears first. Once we setres
to the LCA, we do not update it and do not care about its ancestors.
Last updated