#include <iostream>
using namespace std;
struct Node
{
int data;
Node * leftChild;
Node * rightChild;
public : Node()
{
data = 0;
this->leftChild = 0;
this->rightChild = 0;
}
public :void setData(int i)
{
this->data = i;
}
};
bool cover(Node * root, Node *nd)
{
if (root == nd)
return true;
if (root == NULL)
{
return false;
}
return cover(root->leftChild, nd) || cover(root->rightChild, nd);
}
Node * getRoot(Node * root, Node * nd1, Node * nd2)
{
//if (root == NULL)
//return NULL;
if (!(nd1 && nd2))
return false;
if (cover(root->leftChild, nd1) && cover(root->leftChild, nd2))
return getRoot(root->leftChild, nd1, nd2);
if (cover(root->rightChild, nd1) && cover(root->rightChild, nd2))
return getRoot(root->rightChild, nd1, nd2);
//else
return root;
}
int main()
{
Node *phead = new Node[5];
for (int i = 0; i < 5; ++i)
{
phead[i].setData(i);
}
phead[0].leftChild = & phead[1];
phead[0].rightChild = &phead[2];
phead[1].leftChild = &phead[3];
phead[1].rightChild = &phead[4];
cout << getRoot(phead, &phead[2], &phead[4])->data << endl;
for (int i = 0; i < 5;++i)
for (int j = 0; j < 5; ++j)
{
cout << phead[i].data << " => " << phead[j].data <<"'s common father "<< getRoot(phead, &phead[i], &phead[j])->data << endl;
}
system("pause");
}
FWNX - find the same father - TREE
最新推荐文章于 2024-07-24 14:31:57 发布