二叉树的操作(二叉树的创建、先序遍历--->先根、中序遍历---->先左、后续遍历--->后根)

#include "stdlib.h"	
#include "stdio.h"	
#include "Windows.h"
#include <algorithm>
using namespace std;			/*引入头文件*/
struct tnode						/*定义二叉树存储结构*/
{
	char data;
	struct tnode*lchild;
	struct tnode*rchild;
};
struct tnode tree;						/*定义二叉树指针*/

void createtree(struct tnode*t)				/*创建函数*/
{
	struct tnode*p=t;						/*把二叉树指针给p*/
	char check;
	if(p->lchild==NULL||p->rchild==NULL)	 /*判断左右子树是否为空*/
	{
		printf("please enter the data:");			  /*输入根结点数据*/
		scanf("%c",&(p->data));
		getchar();
    }
	if(p->lchild==NULL)
	{
		printf("%c  leftchild is null.Add? y/n\n",p->data); /*左子树空,询问是否创建*/
		scanf("%c",&check);
		getchar();
		if(check=='y')
		{
			struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*开辟空间*/
			q->lchild=NULL;
			q->rchild=NULL;
			p->lchild=q;
			createtree(q);
		}
	}
	if(p->rchild==NULL)		 
	{
		printf("%c rightchild is NULL.Add? y/n\n",p->data); /*右子树空,询问是否创建*/
		scanf("%c",&check);
		getchar();
		if(check=='y')
		{
			struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*开辟空间*/
			q->lchild=NULL;
			q->rchild=NULL;
			p->rchild=q; 							/*连到二叉树上*/
			createtree(q);
		}
   }
}

void preorder(struct tnode*t)				/*先序遍历函数*/
{
	if(t)
	{
		printf("%c ",t->data);				/*输出根结点数据*/
		preorder(t->lchild);
		preorder(t->rchild);
   }
}

void inorder(struct tnode*t)				 /*中序遍历函数*/
{
	if(t)
	{
		inorder(t->lchild);
		printf("%c ",t->data);
		inorder(t->rchild);
   }
}
void postorder(struct tnode*t) /*后序遍历函数*/
{
	if(t)
	{
		postorder(t->lchild);
		postorder(t->rchild);
		printf("%c ",t->data);
   }
}

void main()
{
	 //clrscr();							/*清屏函数*/
	tree.lchild=NULL;					/*左子树*/
	tree.rchild=NULL;					/*右子树*/
	createtree(&tree); 					/*创建二叉树*/
	preorder(&tree);					/*先序遍历*/
	printf("\n");
	inorder(&tree);					/*中序遍历*/
	printf("\n");
	postorder(&tree);					/*后序遍历*/
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值