数据结构——二叉树寻找两结点的最近祖先

二叉树寻找两结点的最近祖先

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define OK      1
#define TRUE    1
#define FALSE   0
#define ERROR   0

typedef struct Node{        //二叉树的链式存储结点 
	char data; 
	int status;
	int depth;
	struct Node *Lchild;
	struct Node *Rchild;
}BiTNode,*BiTree;

void CreateBiTree(BiTree *root){      //形参采用二级指针,实参为结点孩子域地址 
	char ch;
	ch=getchar();
	
	if(ch=='#')    *root=NULL;
	else{
		*root=(BiTree)malloc(sizeof(BiTNode));
	    (*root)->data=ch; 
	    CreateBiTree(&((*root)->Lchild));
	    CreateBiTree(&((*root)->Rchild));
	}
} 

BiTree p,q;
int count=0;
void Visit(BiTree T){
	if(count==0){
	p=T;
	count++;
	} 
	else {
	q=T;
	count++;
	}
}

void PreOrder(BiTree T,char e){      //先序递归遍历
     if(T){
     	if(T->data==e)  Visit(T);
     	PreOrder(T->Lchild,e);
     	PreOrder(T->Rchild,e);
	 } 	
}


BiTree parent(BiTree T,BiTree root){  //T为当前结点,root为根
    BiTree p1;
    if(root==NULL)  return NULL;
	if(root->Lchild==T||root->Rchild==T)  
	return root;
	p1=parent(T,root->Lchild);
	if(p1!=NULL)
		return p1;
	else return (parent(T,root->Rchild));
}

int h=1;        //当前T结点所在层次 
int depth=0;   //记录当前最大层次 
void TreeDepth(BiTree T,int h){
	if(T){
		T->depth=h;    //记录当前结点的层次 
		if(h>depth)  depth=h;
		TreeDepth(T->Lchild,h+1);
		TreeDepth(T->Rchild,h+1);
	}
}

int main(){
	BiTree T;
	char m,n;
	CreateBiTree(&T);
	getchar();
	m=getchar();
    getchar();
	n=getchar();
	PreOrder(T,m); 
	PreOrder(T,n);
    TreeDepth(T,h);
    p=parent(p,T);
	q=parent(q,T);
	
    while(p->data!=q->data){
    	if(p->depth<q->depth)
    	    q=parent(q,T);
    	else if(p->depth>q->depth)
		    p=parent(p,T);
		else if(p->depth==q->depth){
			p=parent(p,T);
	        q=parent(q,T);
		}	    
	}
    printf("%c",p->data);
    
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/84328119