bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

Leetcode Solutions

Recursive Approach to Find LCA of a Binary Tree

  1. Define a recursive function that takes the current node as an argument.
  2. If the current node is None, return None.
  3. If the current node is equal to p or q, return the current node.
  4. Recursively call the function on the left and right children of the current node to search for p and q.
  5. If both calls return non-null nodes, it means both p and q have been found in different subtrees, so return the current node as the LCA.
  6. If only one of the calls returns a non-null node, return that node.
  7. If both calls return None, return None.
UML Thumbnail

Iterative Approach using Parent Pointers to Find LCA

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...