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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值