二叉树

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct node {
	char data;
	struct node *lchild;
	struct node *rchild;
	
}BtNode;

void Create(BtNode *&b,char str[])
{
	BtNode *St[2000], *p;
	int top =0, k, j =0;
	int end = 0;
	char ch;
	St[top] = b;
	b->data = str[j];
	j++;
	int flag = 0;
	while (str[j] != '\0')
	{
		
		
			if (flag==0)
			{
				if (str[j] != '#')
				{
					p = (BtNode *)malloc(sizeof(BtNode));

					p->data = str[j];
					p->lchild = NULL;
					p->rchild = NULL;
					St[top]->lchild = p;

					end++;
					St[end] = p;
					flag = 1;
				}
				else
				{
					flag = 1;
				}
			}
			else 
			{
				if (str[j] != '#')
				{
					p = (BtNode *)malloc(sizeof(BtNode));
					p->data = str[j];
					p->lchild = NULL;
					p->rchild = NULL;
					St[top]->rchild = p;
					top++;
					end++;
					St[end] = p;
					flag = 0;
				}
				else
				{
					top++;
					flag = 0;
				}
			}

		
		j++;
	}
	
}
void output(BtNode *b, int n)
{
	if (b != NULL)
	{
		for (int i = 1; i <= (n-1)*4; i++)
		{
			printf(" ");
		}
		printf("%c\n", b->data);
		output(b->lchild, n + 1);
		output(b->rchild, n + 1);
	}
	
}


void NLR(BtNode *b)
{
	if (b != NULL)
	{
		
		printf("%c", b->data);
		NLR(b->lchild);
		NLR(b->rchild);
	}
	
}
void LNR(BtNode *b)
{
	if (b != NULL)
	{
		LNR(b->lchild);
		printf("%c", b->data);
		
		LNR(b->rchild);
	}
	
}
void LRN(BtNode *b)
{
	if (b != NULL)
	{

		;
		LRN(b->lchild);
		LRN(b->rchild);
		printf("%c", b->data);
	}

}
int Leaf(BtNode *b)
{
	int num1, num2;
	if (b == NULL)
	{
		return 0;
	}
	else if (b->lchild == NULL&&b->rchild == NULL)
	{
		return 1;
	}
	else
	{
		num1 = Leaf(b->lchild);
		num2 = Leaf(b->rchild);
		return (num1 + num2);
	}
}
void Swap(BtNode *b,BtNode *&t)
{
	if (b == NULL)
		t = NULL;
	else
	{
		t = (BtNode *)malloc(sizeof(BtNode));
		t->data = b->data;
		Swap(b->lchild, t->rchild);
		Swap(b->rchild, t->lchild);
	}
	
}
int main()
{
	BtNode *b = (BtNode *)malloc(sizeof(BtNode));
	char str[100];


	
	gets_s(str);
	b->lchild = b->rchild = NULL;
	Create(b, str);
	printf("BiTree\n");
	output(b, 1);
	printf("pre_sequence  : ");
	NLR(b);
	printf("\n");
	printf("in_sequence   : ");
	LNR(b);
	printf("\n");
	printf("post_sequence : ");
	LRN(b);
	printf("\n");
	printf("Number of leaf: ");
	printf("%d\n", Leaf(b));
	BtNode *t;
	t = (BtNode *)malloc(sizeof(BtNode));
	Swap(b, t);
	printf("BiTree swapped\n");
	output(t, 1);
	printf("pre_sequence  : ");
	NLR(t);
	printf("\n");
	printf("in_sequence   : ");
	LNR(t);
	printf("\n");
	printf("post_sequence : ");
	LRN(t);
	printf("\n");
	int ssss = 1;
	ssss = 2;



	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值