数据结构 C语言 二叉树

二叉树:树形结构是重要的非线性数据结构,树种节点之间具有明确的层次关系,形式上类似于真正的树,二叉树则是每个结点最多有两个子树的树结构。
通过此程序可以实现顺序存储结构,链式存储结构,以及前序遍历,中序遍历,后序遍历。
程序如下

#include<stdio.h>
#include<malloc.h>
#include<process.h>
#define MAXSIZE 100
#define OK 1
#define Error 0

typedef struct BiTNode
{
	char data;
	struct BiTNode *lchild,*rchild; 
}BiTNode,*BiTree;

CreatBiTree(BiTree *T)
{
	char ch;
	scanf("%c",&ch);
	if(ch==' ')
		*T=NULL;
	else
	{
		*T=(BiTNode *)malloc(sizeof(BiTNode));
		(*T)->data=ch;
		CreatBiTree(&(*T)->lchild);
		CreatBiTree(&(*T)->rchild);
	}
	return OK;
}

PreDisplay(BiTree S)
{
	if(S!=NULL)
	{
		printf("%c",S->data);
		PreDisplay(S->lchild);
		PreDisplay(S->rchild);
	}
	return OK;
}

InDisplay(BiTree S)
{
	if(S!=NULL)
	{
		InDisplay(S->lchild);
		printf("%c",S->data);
		InDisplay(S->rchild);
	}
	return OK;
}

LnDisplay(BiTree S)
{
	if(S!=NULL)
	{
		LnDisplay(S->lchild);
		LnDisplay(S->rchild);
		printf("%c",S->data);
	}
	return OK;
}

int Nodes(BiTree S)
{
	int s1,s2;
	if(S==NULL)
		return 0;
	else if(S->lchild==NULL&&S->rchild==NULL)
		return 1;
	else
	{
		s1=Nodes(S->lchild);
		s2=Nodes(S->rchild);
		return s1+s2+1;
	}
}

int leafNodes(BiTree S)
{
	int s1,s2;
	if(S==NULL)
		return 0;
	else if(S->lchild==NULL&&S->rchild==NULL)
		return OK;
	else
	{
		s1=leafNodes(S->lchild);
		s2=leafNodes(S->rchild);
		return s1+s2;
	}
}

TreeEmpty(BiTree S)
{
	return S==NULL;
}

int DeepthBiTree(BiTree S)
{
	int s1,s2;
	if(S==NULL)
		return 0;
	else
	{
		s1=DeepthBiTree(S->lchild);
		s2=DeepthBiTree(S->rchild);
		return (s1>s2)?(s1+1):(s2+1);
	}
}

BiTree FindNode(BiTree t,char e)
{
	BiTree p;
	if(t==NULL)
	{
		printf("tree Empty!\n");
		return NULL;
	}
	else if(t->data==e)
		return t;
	else
	{
		p=FindNode(t->lchild,e);
		if(p!=NULL)
			return p;
		else
			return FindNode(t->rchild,e);
	}
}

BiTree lchildNode(BiTree t)
{
	return t->lchild;
}

BiTree rchildNode(BiTree t)
{
	return t->rchild;
}

int main(void)
{
	BiTree t,m;
	printf("请按先序遍历的次序输入二叉树:\n");
	CreatBiTree(&t);
	printf("二叉树的先序遍历是:\n");
	PreDisplay(t);
	printf("\n");
	printf("二叉树的中序遍历是:\n");
	InDisplay(t);
	printf("\n");
	printf("二叉树的后序遍历是:\n");
	LnDisplay(t);
	printf("\n");
	printf("二叉树T是%s\n",TreeEmpty(t)?"Empty tree!":"No Empty tree");
	printf("二叉树T的节点数=%d\n",Nodes(t));
	printf("二叉树T的叶子节点数=%d\n",leafNodes(t));
	printf("二叉树的深度=%d\n",DeepthBiTree(t));
	printf("二叉树T的左子树根是%c\n",lchildNode(FindNode(t,'a'))->data);
	printf("二叉树T的右子树根是%c\n",rchildNode(FindNode(t,'a'))->data);
	return OK;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值