二叉树的基本操作

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define MAL (NODE*)malloc(sizeof(NODE))
typedef struct node
{
	char data;
	struct node*lchild;
	struct node *rchild;
}NODE;
NODE *Create()//创建一个二叉树
{
	NODE *p;
	char ch;
	ch = getchar();
	if (ch == '0')
		p = NULL;
	else
	{
		p = MAL;
		p->data = ch;
		p->lchild = Create();
		p->rchild = Create();
	}
	return p;
}
void Print(NODE *p)//先序输出二叉树
{
	if (p != NULL)
	{
		printf("%c ", p->data);
		Print(p->lchild);
		Print(p->rchild);
	}
}
void Levelorder(NODE*p)//按层遍历
{
	NODE *quene[100];
	int front=-1, rear=0;
	if (p == NULL)
		return;
	quene[0] = p;
	while (front != rear)
	{
		front++;
		printf("%c ", quene[front]->data);
		if (quene[front]->lchild != NULL)
			quene[++rear] = quene[front]->lchild;
		if (quene[front]->rchild != NULL)
			quene[++rear] = quene[front]->rchild;
	}
}
void spreorder(NODE *t)//非递归先序遍历
{
	int top;
	NODE * stack[20], *p;
	top = 0;
	p = t;
	stack[0] = t;
	while (top >= 0)
	{
		top--;
		printf("%c ", p->data);
		if (p->rchild != NULL)
		{
			stack[++top] = p->rchild;
		}
		if (p->lchild != NULL)
		{
			stack[++top] = p->lchild;
		}
		p = stack[top];
	}
}
int leafNum = 0;
void TotalNum(NODE *p)//计算总节点数
{
	if(p!=NULL)
	{
		leafNum++;
		TotalNum(p->lchild);
		TotalNum(p->rchild);
	}
}
int Depth(NODE *p)//计算深度
{
	int m, n;
	if (p == NULL)
		return 0;
	else
	{
		m = Depth(p->lchild);
		n = Depth(p->rchild);
		if (m > n)
			return m + 1;
		else
			return n + 1;
	}
}
bool Search(NODE *p, char x)
{
	if (p!=NULL&&p->data == x)
		return true;
	if (p->lchild != NULL)
		return(Search(p->lchild, x));
	if (p->rchild != NULL)
		return(Search(p->rchild, x));


	return false;
}
//abc00de0g00f000
int main(void)
{
	NODE*p;
	p = Create();
	Print(p);


	printf("\n树的深度为%d\n", Depth(p));


	TotalNum(p);
	printf("树的总节点个数为%d\n",leafNum);


	printf("\n按层遍历:");
	Levelorder(p);


	printf("\n非递归先序遍历:");
	spreorder(p);


	if (Search(p, 'g'))
		printf("\n存在 g ");
	else
		printf("\n不存在 g ");


	system("pause");
}
二叉树的操作大多建立在递归的基础之上,所以需要稍微了解下递归!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值