二叉树的基本运算——数据结构

二叉树采用二叉链表作为存储结构,实现二叉树的如下基本操作:
(1)按先序序列构造一颗二叉链表表示的二叉树T;
(2)对这颗二叉树进行先序和层次遍历序列,分别输出结点的遍历序列;
(3)求二叉树的深度。

#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef char TElemType;
typedef int Status;
typedef struct BiTNode
{
	TElemType data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;


void CreateBiTree(BiTree *T)
{
	char ch;
	ch=getchar();
	if(ch=='#')
		(*T)=NULL;
	else
	{
		(*T)=(BiTree)malloc(sizeof(BiTNode));
		(*T)->data=ch;
		CreateBiTree(&(*T)->lchild);
		CreateBiTree(&(*T)->rchild);
	}
}


void PreOrder(BiTree T)
{
	if(T)
	{
		printf("%2c",T->data);
		PreOrder(T->lchild);
		PreOrder(T->rchild);
	}
}


void LevelOrder(BiTree T)
{
	BiTree Queue[MAX],b;
	int front,rear;
	front=rear=0;
	if(T)
	{
		Queue[rear++]=T;
		while(front!=rear)
		{
			b=Queue[front++];
			printf("%2c",b->data);
			if(b->lchild!=NULL) Queue[rear++]=b->lchild;
			if(b->rchild!=NULL) Queue[rear++]=b->rchild;
		}
	}
}


int depth(BiTree T)
{
	int dep1,dep2;
	if(T==NULL) return 0;
	else
	{
		dep1=depth(T->lchild);
		dep2=depth(T->rchild);
		return dep1>dep2?dep1+1:dep2+1;
	}
}


void main()
{
	BiTree T=NULL;
	printf("\n创建一颗二叉树:\n");

	CreateBiTree(&T);
	printf("\n先序遍历结果为:\n");

	PreOrder(T);
	printf("\n层次遍历结果为:\n");

	LevelOrder(T);
	printf("\n树的深度为:  %d\n",depth(T));
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值