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

#include //lca lowest common ancestor 时复o(n)
#include
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 &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 path1, path2;
bool find1 = findpath(root,path1,key1);
bool find2 = findpath(root,path2,key2);
if(find1 && find2){
int ans;
for(int i=0;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)="< return 0;

return 0;
}

你可能感兴趣的:(Judge,Online)