Question
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Solution
一开始脑抽了,没有看到是查找树,以为是一般的树,所以复杂了一点,下面是对所有树都通用的。
思路是:
- 找到第一个目标节点A;
- 以该目标节点为根dfs查找第二个目标节点B;如果找得到,说明两者的LCA是节点A,否则不做其他事,返回上一层;
- 如果LCA不是节点A,由于A是找到的第一个目标节点,按照我们的搜索顺序,第二个目标节点B必然在A的某个祖先节点的右子树上。故对这些祖先节点,即满足dfs(root->left, val, val2, ans)的节点,调用dfsr(root, val2)查找结点B即可。由递归的性质,我们可以保证第一个满足条件的节点必然为LCA。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* ans = NULL;
TreeNode* v1 = p; //Be careful don't write like this:TreeNode* v1 = p, v2 = q;
TreeNode* v2 = q; //You could write like this:TreeNode *v1 = p, *v2 = q;
dfs(root, v1, v2, &ans);
return ans;
}
private:
//Find the first value
bool dfs(TreeNode* root, TreeNode* &v1, TreeNode* &v2, TreeNode** ans) {
if (!root) return false;
if (root == v1 || root == v2) {
if (root == v2) { //Let val2 be the second value
TreeNode* tmp = v1;
v1 = v2;
v2 = tmp;
}
if (dfsr(root, v2)) *ans = root; //if current node is LCA
return true;
}
if (dfs(root->left, v1, v2, ans)) { //the second node must be in the right-subtree of one of ancestor of the first node
if (!(*ans) && dfsr(root, v2)) *ans = root;
return true;
}
if (dfs(root->right, v1, v2, ans)) return true;
return false;
}
bool dfsr(TreeNode* root, TreeNode* v) {
if (!root) return false;
if (root == v) return true;
if (dfsr(root->left, v)) return true;
if (dfsr(root->right, v)) return true;
return false;
}
};
如果是二叉查找树,那么就简单很多,只需要将A,B值分别与当前节点比较,如果在同一边,则可以递归下去,如果不在同一边,说明当前节点已经是LCA了。
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return root;
if((root->val - p->val)*(root->val - q->val)<=0) return root;
if((root->val - p->val)>0 && (root->val - q->val)>0) return lowestCommonAncestor(root->left,p,q);
if((root->val - p->val)<0 && (root->val - q->val)<0) return lowestCommonAncestor(root->right,p,q);
}
Note:看题仔细,不要脑抽!不过作为练习,考虑一般情况是可以的。
意外收获:
发现236. Lowest Common Ancestor of a Binary Tree
是本题的进阶版,一般情况下的树~直接提交啦~