Problem Summary
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
What if the tree is just a binary tree ?
Solution
Subproblem 1 is trivial if we know the definition of BST.
Subproblem 2 needs more thinking. There are two ways to solve it.
The first is traditional. We define a variant LCA and a function dfs(TreeNode *ROOT,TreeNode *p,TreeNode *q). dfs returns the number of given nodes that are in the subtree with ROOT as root. If dfs returns 2 and LCA have not been changed, then the answer is ROOT.
Let us define a recursive function f(TreeNode *ROOT,TreeNode *p,TreeNode *q).
- If the subtree with ROOT as root contains both p and q, f returns the LCA of p and q.
- If the subtree only contains one of them, f returns that one.
- If the subtree contains neither of them, f returns NULL.
For each ROOT, we first check whether it is NULL or equal to p or q. If that is the case, return ROOT. Then we call f(ROOT->left,p,q) and f(ROOT->right,p,q), and store the results in LEFT and RIGHT. If they are both not NULL, we know that both subtrees contain one of p and q. Thus ROOT is the LCA we are looking for. If only one of them are not NULL, then return it. If both are NULL, return NULL.
Code 1 — LCA of a binary search tree
|
|
Code 2 — LCA of a binary tree, Solution 1
|
|
Code 3 – LCA of a binary tree, Solution 2
|
|