c++求带父亲节点的两个节点的最近祖先
思路是先找到这两个叶子节点的在二叉树的位置,然后沿着祖先用一个栈保存从叶子节点到根节点的路径。比较两个叶子节点的路径节点,找出最后一次相等的节点,这个节点就是他们的公共祖先。
#include<iostream>
#include<stack>
using namespace std;
//求两个叶子节点的最近共同祖先,默认节点的值都不同,有指向父亲的节点。
/*
测试用例:1 2 4 # # 5 # # 3 # #
*/
struct Node{
char data;
Node *lchild;
Node *rchild;
Node *parent;
};
Node*createTree(){
char x;
cin>>x;
if(x=='#')return NULL;
Node *root=new Node;
root->data=x;
root->lchild=createTree();
root->rchild=createTree();
if(root->lchild!=NULL)
root->lchild->parent=root;
if(root->rchild!=NULL)
root->rchild->parent=root;
return root;
}
Node *position(char x,Node *root){
if(root){
static Node*p1,*p2;
if(root->data==x) return root;
p1=position(x,root->lchild);
if(p1!=NULL)return p1;
p2=position(x,root->rchild);
if(p2!=NULL)return p2;
}
return NULL;
}
char getLowestCommonAncestors(char x ,char y,Node *root){
Node *position_x,*position_y;
position_x=position(x,root);
position_y=position(y,root);
stack<Node*>s_x,s_y;
while(position_x->parent!=NULL){
s_x.push(position_x->parent);
position_x=position_x->parent;
}
while(position_y->parent!=NULL){
s_y.push(position_y->parent);
position_y=position_y->parent;
}
Node *p=NULL;
while(!s_x.empty()&&!s_y.empty()){
if(s_x.top()!=s_y.top())break;
p=s_x.top();
s_x.pop();
s_y.pop();
}
return p->data;
}
int main(){
Node *root=createTree();
char x,y;
cout<<"输入两个节点"<<endl;
cin>>x>>y;
char z=getLowestCommonAncestors(x,y,root);
cout<<"最近的公共祖先为:"<<z<<endl;
return 0;
}

该博客介绍了如何使用C++编程解决二叉树问题,特别是寻找两个给定节点的最近公共祖先。通过遍历每个节点并使用栈保存路径,最后找到两个路径中最后一个相同的节点作为公共祖先。提供的代码示例详细展示了实现过程,并提供了测试用例。
403

被折叠的 条评论
为什么被折叠?



