您的位置:首页 > 其它

LCA树两个节点最低公共祖先

2016-01-24 17:40 363 查看
#include<iostream>
#include<vector>
using namespace std;

struct Tree
{
Tree *pLeft;
Tree *pRight;
int nValue;
};

bool FindPath(Tree *root,int nFindValue,vector<int> &vec)
{
if(root == NULL)
{
return false;
}
bool flag = false;//判断是否找到要找到的节点值(路径)
vec.push_back(root->nValue); //将值放到vector中
if(root->nValue == nFindValue)//如果找到返回 true ,此时上一层的 flag 为true
{
return true;
}
if(!flag && root->pLeft != NULL)//如果找到值了,flag 为true 就不会继续查找了
{
flag = FindPath(root->pLeft,nFindValue,vec);
}
if(!flag && root->pRight != NULL)//如果找到值了,flag 为true 就不会继续查找了
{
flag = FindPath(root->pRight,nFindValue,vec);
}
if(flag == false)//如果找到值了 , 此时的路径  不应该 从 vector中 删除
{
vec.pop_back();
}
return flag;
}
int PanDuan(Tree *root,int nFindValue1,int nFindValue2)
{
vector<int> vec1,vec2;
int nValue = -1;
int flag1 = FindPath(root,nFindValue1,vec1);
int flag2 = FindPath(root,nFindValue2,vec2);
////////////////////////////////////////////////
for(int i=0;i<vec1.size();i++)
{
cout<<vec1[i]<<" ";
}
cout<<endl;
for(int i=0;i<vec2.size();i++)
{
cout<<vec2[i]<<" ";
}
cout<<endl;
////////////////////////////////////////////////
if(flag1 && flag2)
{
for(int i = 0 ; i< vec1.size()< vec2.size()?vec1.size():vec2.size();i++)
{
if(vec1[i] != vec2[i])
{
break;
}
else
{
nValue = vec1[i];
}
}
}
return nValue;
}
Tree *newNode(int nValue)
{
Tree *temp = new Tree;
temp->nValue = nValue;
temp->pLeft = NULL;
temp->pRight = NULL;
return temp;
}
int main()
{
Tree * root = newNode(1);
root->pLeft = newNode(2);
root->pRight = newNode(3);
root->pLeft->pLeft = newNode(4);
root->pLeft->pRight = newNode(5);
root->pRight->pLeft = newNode(6);
root->pRight->pRight = newNode(7);
cout<<PanDuan(root,4,6)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: