Lowest Common Ancestor
Intro
This is classic problem of binary tree. It has a lot of practical usages and motivations behind it. For example, we want to find the lowest tag that two elements have access to in a DOM tree. Or we want to find the smallest interval in a segment tree.
LCA of a Binary Tree (LC.236)
Given a binary tree, find the lowest common ancestor of two given nodes in the tree.
Example
+ 4
/ \
3 7
/ \
5 6
Input: LCA(3,5) Output: 4
Input: LCA(5,6) Output: 7
Input: LCA(6,7) Output: 7Assume two nodes are in the tree.
Analysis
Obviously, traversing won't work well because we can't visit each node only once from top down. Now we have to come up with a task, the same task, for both the left subtree and the right subtree.
4 cases for the root:
LCA in is leftSubtrees
LCA is in rightSubtree
root is the LCA
LCA doesn't exist
If you can find LCA, return the LCA. If you can only find p/q, then return p/q.
Problematic Code
This piece of code is problematic for several reasons. The first one is the way we define the state. The return type can be a LCA or a target node we have found. This will cause problems in the follow up question.
Follow up #1 (LI.578)
What if node1 or node2 might not exist in the tree? Return null in that case.
Analysis
Previous, the program will return node1 or node2 if the other does not exist in the tree. Now we need to distinguish these two cases. 1. node2 is a descendant of node1 2. node2 is not in the current tree
Examples Lesson
Always do a few examples (exhaust all cases) before talk about your approach.
Approach
Refined Code
Follwo Up #2 (LI.474)
Given parent pointers
Follow Up #3
Find all common ancestors. You can need to store the path to root in an array list. Then find intersection of two arrays.
References
Finding the Lowest Common Ancestor by stoimen
Crack the Coding Interview Ch4 Q7 Solution
Last updated