递归先序、非递归层次建立二叉树并用三序遍历之(C语言)

 先序就是直接用递归的方法建立,层次使用了辅助数组,后一种方法我觉得友好多了。

#include "stdio.h"

#define MAXSIZE    50
#define TRUE       1
#define FALSE      0
 
typedef int bool;       //Cpp中这一行要取消掉,他内置bool型 
typedef int Status;    //函数类型,其值是函数结果状态码
typedef char ElemType;  //数据类型

typedef struct BinTree				//定义二叉树结构 
{
	ElemType Data;
	struct BinTree *LChild,*RChild;
}BTNode;

void vist( ElemType  Temp)
{
	printf("%c ",Temp);
}

void Pre(BTNode *BT)//先序遍历 
{
	if(BT)
	{
		vist(BT->Data);
		Pre(BT->LChild);
		Pre(BT->RChild);
	}
}

void In(BTNode *BT)//中序遍历 
{
	if(BT)
	{
		In(BT->LChild);
		vist(BT->Data);
		In(BT->RChild);
	}
}

void Post(BTNode *BT)//后序遍历 
{
	if(BT)
	{
		Post(BT->LChild);
		Post(BT->RChild);
		vist(BT->Data);

	}
}


BTNode * LevelCreate()//按层次遍历建树 
{
    printf("*******层 次 遍 历 建 树*******\n");
   	printf("*编号数字,结点值字母,0结束。*\n\n\n"); 
	BTNode *T,*p,*s[MAXSIZE];
	char ch;
	int i,j,cnt=0; 
	while (1)
	{
	if(cnt%2==0)
			{
			printf("请输入编号:");
			 cnt++;
			}
       else{
       		printf("请输入结点值:");
			 cnt++;
			}
	scanf("%d",&i);
	if(i==0)  break;
		else {
		ch=getchar();		
		p=(BTNode*)malloc(sizeof(BTNode));
		p->Data=ch;
		p->LChild=p->RChild=NULL;
		s[i]=p;
			if (i==1) T=p;
			else 
				{
					j=i/2;
				   	if(i%2==0)
						s[j]->LChild=p;
						else s[j]->RChild=p;
				}
		   }
	}
return (T);
}

BTNode *PreCreate()  //先序建树,输入*代表那个结点不存丰。 
{
    char ch;
    BTNode *T;
 scanf("%c",&ch);
  if(ch!='*')
	    {
	        T=(BTNode*)malloc(sizeof(BTNode));
	        T->Data=ch;
	        T->LChild=PreCreate();
	        T->RChild=PreCreate();
	    }
    else
	    {
	        T=NULL; //为零则不存在 
	    }
    return T;
}

int main()
{

	BTNode *TRoot,*PRoot;

      printf("#########先序遍历建树#########\n"); 
      printf("请一次输入全部结点值,空结点为*.\n"); 
      printf("如树序列123,则输入123****\n"); 
       printf("\n\请输入:"); 
TRoot=PreCreate();
   	printf("先序遍历:");
       Pre(TRoot);
    		printf("\n中序遍历:");
      			In(TRoot);
   						printf("\n后序遍历:");
     							  Post(TRoot);      
   	printf("\n");
     	
PRoot=LevelCreate();
    printf("先序遍历:");
       Pre(PRoot);
    	printf("\n中序遍历:");
      		 In(PRoot);
   				printf("\n后序遍历:");
      				 Post(PRoot);
       
   	printf("\n\n\n");
	getchar();
	return 0;
}

运行效果如下图:

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

G00dChina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值