问题1:求平衡二叉树的最低公共祖先。
问题2:求普通二叉树的最低公共祖先。
问题3:求普通树的最低公共祖先。
代码如下:
问题1:
#include<iostream>
using namespace std;
struct BTNode
{
int key;
BTNode *lchild;
BTNode *rchild;
};
BTNode * find(BTNode *r,BTNode *p,BTNode *q)
{
if(r->key>p->key&&r->key>q->key)
return find(r->lchild,p,q);
else if(r->key<p->key&&r->key<q->key)
return find(r->rchild,p,q);
else
return r;
}
int main()
{
BTNode d={8,NULL,NULL},e={11,NULL,NULL},f={15,NULL,NULL},g={20,NULL,NULL},b={10,&d,&e},c={18,&f,&g},a={12,&b,&c};
cout<<find(&a,&g,&d)->key<<endl;
return 0;
}
问题2:
#include<iostream>
using namespace std;
struct TreeNode
{
int key;
TreeNode * lchild;
TreeNode * rchild;
};
TreeNode* getLCA(TreeNode* root,TreeNode *X,TreeNode *Y)
{
if(root==NULL) return NULL;
if(X==root||Y==root) return root;
TreeNode *left=getLCA(root->lchild,X,Y);
TreeNode *right=getLCA(root->rchild,X,Y);
if(left==NULL) return right;
else if(right==NULL) return left;
else return root;
}
int main()
{
TreeNode g={7,NULL,NULL},f={6,NULL,NULL},e={5,&f,&g},d={4,NULL,NULL},c={3,NULL,NULL},b={2,&d,&e},a={1,&b,&c};
TreeNode *p;
p=getLCA(&a,&g,&f);
cout<<p->key<<endl;
return 0;
}
问题3:
#include<iostream>
#include<vector>
#include<list>
using namespace std;
struct TNode
{
int key;
vector<TNode *> m_vchildren;
};
int GetNodePath(TNode *pRoot,TNode *pNode,list<TNode *>&path)
{
if(pRoot==pNode)
return true;
path.push_back(pRoot);
int found=false;
vector<TNode *>::iterator i=pRoot->m_vchildren.begin();
while(!found && i<pRoot->m_vchildren.end())
{
found=GetNodePath(*i,pNode,path);
++i;
}
if(!found) //如果没找到
path.pop_back();
return found;
}
TNode * GetLastCommonNode(const list<TNode *> &path1,const list <TNode *> &path2)
{
list<TNode*>::const_iterator iterator1=path1.begin();
list<TNode*>::const_iterator iterator2=path2.begin();
TNode * pLast=NULL;
while(iterator1!=path1.end() && iterator2!=path2.end())
{
if(*iterator1!=*iterator2)
{
pLast=*(--iterator1);
break;
}
iterator1++;
iterator2++;
}
if(iterator1==path1.end())
pLast=*(--iterator2);
if(iterator2==path2.end())
pLast=*(--iterator2);
return pLast;
}
TNode *GetLastCommonParent(TNode *pRoot,TNode *pNode1,TNode *pNode2)
{
if(pRoot==NULL ||pNode1==NULL ||pNode2==NULL)
return NULL;
list<TNode *> path1;
list<TNode *>::iterator iter;
GetNodePath(pRoot,pNode1,path1);
list<TNode *> path2;
GetNodePath(pRoot,pNode2,path2);
return GetLastCommonNode(path1,path2);
}
int main()
{
TNode a,b,c,d,e,f,g,h,i,j,k;
i.key=9;
j.key=10;
k.key=11;
h.key=8;
g.key=7;
f.key=6;
f.m_vchildren.push_back(&i);
f.m_vchildren.push_back(&j);
f.m_vchildren.push_back(&k);
e.key=5;
d.key=4;
c.key=3;
c.m_vchildren.push_back(&g);
c.m_vchildren.push_back(&h);
b.key=2;
b.m_vchildren.push_back(&d);
b.m_vchildren.push_back(&e);
b.m_vchildren.push_back(&f);
a.key=1;
a.m_vchildren.push_back(&b);
a.m_vchildren.push_back(&c);
cout<<GetLastCommonParent(&a,&d,&i)->key<<endl;
return 0;
}