您的位置:首页 > 其它

在树中寻找两个节点的最低公共祖先

2013-08-17 10:53 375 查看


//通过寻找从根至节点的路径,取两个节点路径上的最后一个相同的节点,即为最低公共祖先
#include <time.h>
#include <stdlib.h>
#include <vector>
#include "BinarySearchTree.h"
#include <iostream>
using namespace std;

void printv(const vector<Position>& v)
{
vector<Position>::const_iterator cit = v.begin();
while(cit != v.end())
cout<<(*cit)->data<<" ", ++cit;
cout<<endl;
}
//从根开始搜索到某一节点的路径(采用了二叉查找树,但没利用其性质故可以推广至具有任一数量的儿子的树中)
bool find_path(BinarySearchTree t, vector<Position>& v, const int x)
{
if(t != NULL && t->data != x)
{
v.push_back(t);
bool res = (find_path(t->left, v, x) || find_path(t->right, v, x));
if(true != res)
v.pop_back();
return res;
}
else if(t == NULL)
return false;
v.push_back(t);
return true;
}

int main(int argc, char const *argv[])
{
std::vector<Position> v1, v2;
BinarySearchTree t = NULL;
MakeEmpty(&t);
srand((unsigned)time(NULL));
for(int i = 0; i != 100; ++i)
Insert(rand()%30, &t);
PrintTree(t, 2, 0);
find_path(t, v1, 8);
cout<<"path to 8: ";
printv(v1);
find_path(t, v2, 15);
cout<<"path to 15: ";
printv(v2);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: