1. 程式人生 > >c語言實現二叉樹的先序遍歷,中序遍歷,後序遍歷

c語言實現二叉樹的先序遍歷,中序遍歷,後序遍歷

// new.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <MEMORY.H>
#include <STRING.H>
#include <STDLIB.H>
#include <WINDOWS.H>


/*
 先序遍歷 DLR
 中序遍歷 LDR
 後序遍歷 LRD
*/
typedef struct Node{
char data;
struct Node* lChild,*rChild;
}Tree,*PTree;
void CreateNode(struct Node** pNode)
{
   //以空格作為樹的結束
char ch;
printf("請輸入節點:");
scanf("%c",&ch);
getchar();
if(ch == ' ')
{
pNode = NULL;
   return;
}
else
{
    

*pNode = (PTree)malloc(sizeof(struct Node));
memset(*pNode,0,sizeof(struct Node));
    (*pNode)->data = ch;
CreateNode(&((*pNode)->lChild));
    CreateNode(&((*pNode)->rChild));
    }


}
//先序遍歷
void prevSearch(PTree* pNo)
{
PTree PNode = *pNo;
    if(PNode)
{
       printf("%c\t",PNode->data);
  prevSearch(&(PNode->lChild));
  prevSearch(&(PNode->rChild));
     
}


}
//中序遍歷
void CenterSearch(PTree* pNo)
{
PTree PNode = *pNo;
   if(PNode)
   {
      CenterSearch(&(PNode->lChild));
 printf("%c\t",PNode->data);
 CenterSearch(&(PNode->rChild));


   }


}
// 後序遍歷
void postSeaech(PTree* pNo)
{
PTree pNode = *pNo;
if(pNode)
{
     postSeaech(&(pNode->lChild));
postSeaech(&(pNode->rChild));
     printf("%c\t",pNode->data);
    
}
}
void Destory(PTree* pNo)
{
    PTree pNode = *pNo;
if(pNode)
{
       Destory(&(pNode->lChild));
  Destory(&(pNode->rChild));
  free(pNode);


}
}
bool Menu(PTree* root)
{
    char Option;
printf("A . 創造樹\n");
printf("B . 先序遍歷\n");
printf("C . 中序遍歷\n");
printf("D . 後續遍歷\n");
printf("E . 退出\n");

    printf("請輸入你的選項:");
    scanf("%c",&Option);
getchar();
switch(Option)
{
case 'A': CreateNode(root);
return true;
    case 'B':
if(!root){printf("該樹是空的,請先建立樹"); break;}
prevSearch(root); 
return true;
case 'C': 
if(!root){printf("該樹是空的,請先建立樹"); break;}
CenterSearch(root);
return true;
case 'D':
if(!root){printf("該樹是空的,請先建立樹"); break;}
postSeaech(root);
return true;
case 'E':
   printf("程式正在結束!");
Destory(root);
printf("程式已經結束!");
return false;


}
return true;
}
int main(int argc, char* argv[])
{
PTree root = NULL;
bool flag = true;
while(flag)
{
flag=Menu(&root);
}


return 0;
}