庆祝!!!最后一篇剑指offer系列博客!
/*
这本书,,终于看到最后一个题了。太激动了。
这还是以面试的实际案例给出的
当给除这个题目的时候 首先看是不是二叉树
如果是bst 那直接找比一个小 比另一个大的
如果说只说普通的树 先问有没有指向父亲的指针 有的话就相当与 两个链表的第一个重合节点么
如果没有指向父节点的指针 那也好办 直接遍历 然后记录路径就行了
最后两个路径的最后一个相同的点就是ans了
*/
#include<iostream>
#include<cstdio>
#include<vector>
#include<list>
using namespace std;
struct TreeNode
{
int data;
vector<TreeNode *> child;
TreeNode(int t)
{
data=t;
}
};
//这里返回根节点的指针 然后传入两个要找的点的 指针的引用 第一次这么写 可以的 很好用
TreeNode * CreateTree(TreeNode * &p1,TreeNode * &p2)
{
TreeNode * root=new TreeNode(1);
TreeNode * tmp=new TreeNode(2);
root->child.push_back(tmp);
tmp=new TreeNode(3);
root->child.push_back(tmp);
tmp=root->child[0];
TreeNode * tmp1=new TreeNode(4);
tmp->child.push_back(tmp1);
tmp1=new TreeNode(5);
tmp->child.push_back(tmp1);
TreeNode * tmp2=tmp->child[1];//保存5
tmp=tmp->child[0];
tmp1=new TreeNode(6);
p1=tmp1;
tmp->child.push_back(tmp1);
tmp1=new TreeNode(7);
tmp->child.push_back(tmp1);
tmp=tmp2;
tmp1=new TreeNode(8);
p2=tmp1;
tmp->child.push_back(tmp1);
tmp1=new TreeNode(9);
tmp->child.push_back(tmp1);
tmp1=new TreeNode(10);
tmp->child.push_back(tmp1);
return root;
}
void ShowTree(TreeNode * root)
{
printf("%d\t",root->data);
for(int i=0;i<root->child.size();++i)
ShowTree(root->child[i]);
}
bool GetNodePath(TreeNode * root,TreeNode *p,list<TreeNode *> & path)
{
if(root==p)// 找到这个点了 返回
return true;
path.push_back(root);
bool find=false;
vector<TreeNode *> ::iterator it=root->child.begin();
while(!find && it!=root->child.end())
{
find=GetNodePath(*it,p,path);
++it;
}
if(!find)//没找到就退一下
path.pop_back();
return find;
}
TreeNode * GetLastCommonParend(TreeNode * root, TreeNode * p1, TreeNode * p2)
{
if(root==NULL || p1==NULL || p2==NULL)
return NULL;
list<TreeNode * > path1;//记录根节点到两个节点的路径
list<TreeNode * > path2;
GetNodePath(root,p1,path1);//调用这个函数 最后 path1 和path2 里面存了路径
GetNodePath(root,p2,path2);
if(path1.empty() || path2.empty())//说明有最少一个点 就是root
return root;
//接下来就把这两个路径中最后一个相等的元素找出来就行了
TreeNode * plast=NULL;
list<TreeNode *>::iterator it1=path1.begin();
list<TreeNode *>::iterator it2=path2.begin();
while(it1!=path1.end() && it2!=path2.end())
{
if(*it1==*it2)//这里只要地址一样就可以了
plast=*it1;
it1++;
it2++;
}
return plast;
}
int main()
{
TreeNode * p1,* p2;
TreeNode * root=CreateTree(p1,p2);
//到这里 root p1 p2 就弄好了 现在要得到p1 p2的最低公共祖先
// ShowTree(root);
TreeNode * ans=GetLastCommonParend(root,p1,p2);
if(ans!=NULL)
cout<<ans->data<<endl;
return 0;
}