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

版权声明:原创的东西,转载时留个标记。 https://blog.csdn.net/laguoqing/article/details/85008035

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

#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;
}

运行效果如下图:

 

 

猜你喜欢

转载自blog.csdn.net/laguoqing/article/details/85008035