c++求带父亲节点的两个节点的最近祖先

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;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值