1.是二叉搜索树
struct TreeNode
{
int val;
TreeNode *left, *right;
};
TreeNode *LCA(TreeNode *root, TreeNode *p1, TreeNode *p2)
{
while(1) {
if (root->val > p1->val && root->val > p2->val) root = root->left;
else if (root->val < p1->val && root->val < p2->val) root = root->right;
else return root;
}
}
2.不是二叉搜索树,是二叉树
2.1有父指针
分别从两个结点出发,得到两个到根结点的单向链表,转换为求两个单向链表的第一个公共结点。
2.2没有父指针
(1)http://zhedahht.blog.163.com/blog/static/25411174201081263815813/
(2)
TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2)
{
if(!root||root==p1||root==p2)return root;
TreeNode *left=LCA(root->left,p1,p2);
TreeNode *right=LCA(root->right,p1,p2);
if(left&&right)return root;
else if(left)return left;
else if(right)return right;
else return NULL;
}
(3)Tarjan算法
(4)转换为RMQ问题
http://blog.csdn.net/hz5034/article/details/44084087
3.不是二叉树,是树
struct TreeNode
{
int val;
vector<TreeNode *>children;
};
bool dfs(TreeNode *root,TreeNode *&p,vector<TreeNode *> &path)
{
if(!root)return false;
path.push_back(root);
if(root==p)return true;
for(vector<TreeNode *>::iterator i=root->children.begin();i!=root->children.end();++i)
{
if(dfs(*i,p,path))return true;
}
path.pop_back();
return false;
}
TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2)
{
if(!root||!p1||!p2)return NULL;
vector<TreeNode *> path1,path2;
dfs(root,p1,path1);
dfs(root,p2,path2);
TreeNode *res;
for(int i=0;i<path1.size()&&i<path2.size();++i)
{
if(path1[i]==path2[i])res=path1[i];
else break;
}
return res;
}