二叉树 之 lowest common ancestor 最低公共祖先

#include <iostream> //lca lowest common ancestor 时复o(n)
#include <vector>
using namespace std;
struct node{//二叉树结点
int key;
struct node *left, *right;
};
node * newnode(int k){//公用函数,生成一个节点
node *temp = new node;
temp->key = k;
temp->left = temp->right = NULL;
return temp;
}
bool findpath(node* root, vector<int> &path, int key){
//从root到节点值为key的路径,存储在path中,如果没有返回-1
if(root == NULL) return false;
path.push_back(root->key);
if(root->key == key) return true;
bool find = (findpath(root->left,path,key) ||
findpath(root->right,path,key));
if(find) return true;
//该结点下未找到就弹出
path.pop_back();
return false;
}
int findlca(node *root, int key1, int key2){
vector<int> path1, path2;
bool find1 = findpath(root,path1,key1);
bool find2 = findpath(root,path2,key2);
if(find1 && find2){
int ans;
for(int i=0;i<path1.size();i++){
if(path1[i] != path2[i]){
break;
}
else
ans = path1[i];
}
return ans;
}
return -1;
}
int main(){
node* root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
root->right->left = newnode(6);
root->right->right = newnode(7);
cout<<"lca(4,5)=" << findlca(root,4,5);
cout<<"\nlca(4,6)="<<findlca(root,4,6)<<endl;
return 0;

return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值