The binary tree of the data structure is traversed in order, and the level of the output node and the parent node of a node

#include <stdio.h>
#include <stdlib.h>
typedef char DataType;

typedef struct Node
{
	DataType data;
	struct Node * LChild;
	struct Node * RChild;
}BiTNode,* BiTree;

//创建
void CreateNode (BiTree *T)
{
	DataType ch;
	scanf("%c",&ch);
	if(ch=='#')
        *T=NULL;
	else{
		*T=(BiTree) malloc (sizeof(Node ));
		 
		(*T)->data=ch;
		CreateNode(&(*T)->LChild);
		CreateNode(&(*T)->RChild);
		
	}
}

//输出
void Ch(DataType ch,int i)
{
	printf(" %c || ",ch);
	printf(" 结点%c在第 %d 层\n",ch,i);
}
//先序遍历二叉树
void PreOrder(BiTree T,int i)
{
	if(T!=NULL)
	{
		Ch(T->data,i);
		PreOrder(T->LChild,i+1);
		PreOrder(T->RChild,i+1);
	}
}

void FindParent(BiTree T,DataType e,Node * &p)
{
	if(T!=NULL)
	{
		if(T->data==e)  p==NULL;
		else if(T->LChild!=NULL && T->LChild->data==e)
			p=T;
		else if(T->RChild!=NULL && T->RChild->data==e)
			p=T;
		else
		{
			FindParent(T->LChild,e,p);
			if(p==NULL)
			{
				FindParent(T->RChild,e,p);
			}
		}
	}
	else
	{
		p=NULL;
	}
}

void solve(BiTree T,DataType e)
{
	Node *p;
	FindParent(T,e,p);
	if(p!=NULL)
		printf(" 结点 %c 的双亲为: %c\n",e,p->data);
	else 
		printf(" 结点 %c 的没有双亲结点,该节点为根节点或者不存在",e);
}


int main()
{
	BiTree T;
	int i=1;
	printf("按先序遍历输入(没有孩子的输入#): ");
	CreateNode(&T);
	printf("先序遍历: \n");
	PreOrder(T,i);
	DataType e1='G';
	solve(T,e1);
	DataType e2='H';
	solve(T,e2);
	printf("\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44068262/article/details/106361232