二叉樹的建立、遍歷、求深度、打印(17計科教學用)

#include<stdio.h>
#include <malloc.h>
#include <conio.h>
typedef int DataType; 
typedef struct Node
{
 DataType data;
 struct Node *LChild;
 struct Node *RChild;
}BitNode,*BitTree;
void CreatBiTree(BitTree *bt)//用擴展先序遍歷序列創建二叉樹,如果是#當前樹根置爲空,否則申請一個新節點//
{
 char ch;
 ch=getchar();
 if(ch=='#')*bt=NULL;
 else
 {
  *bt=(BitTree)malloc(sizeof(BitNode));
  (*bt)->data=ch;
  CreatBiTree(&((*bt)->LChild));
  CreatBiTree(&((*bt)->RChild));
 }
}
void Visit(char ch)//訪問根節點
{
 printf("%c  ",ch);
}
void  PreOrder(BitTree root) /*先序遍歷二叉樹, root爲指向二叉樹(或某一子樹)根結點的指針*/
{
 if (root!=NULL)
 {
  Visit(root ->data);  /*訪問根結點*/
  PreOrder(root ->LChild);  /*先序遍歷左子樹*/
  PreOrder(root ->RChild);  /*先序遍歷右子樹*/
 }
}
void  InOrder(BitTree root)  
/*中序遍歷二叉樹, root爲指向二叉樹(或某一子樹)根結點的指針*/
{
 if (root!=NULL)
 {
  InOrder(root ->LChild);   /*中序遍歷左子樹*/
  Visit(root ->data);        /*訪問根結點*/
  InOrder(root ->RChild);   /*中序遍歷右子樹*/
 }
}

void  PostOrder(BitTree root)  
/* 後序遍歷二叉樹,root爲指向二叉樹(或某一子樹)根結點的指針*/
{
 if(root!=NULL)
 {
  PostOrder(root ->LChild); /*後序遍歷左子樹*/
  PostOrder(root ->RChild); /*後序遍歷右子樹*/
  Visit(root ->data);       /*訪問根結點*/
 }
}
int PostTreeDepth(BitTree bt)   //後序遍歷求二叉樹的高度遞歸算法//
{
 int hl,hr,max;
 if(bt!=NULL)
 {
  hl=PostTreeDepth(bt->LChild);  //求左子樹的深度 
  hr=PostTreeDepth(bt->RChild);  //求右子樹的深度 
  max=hl>hr?hl:hr;              //得到左、右子樹深度較大者
  return(max+1);               //返回樹的深度
 }
 else return(0);              //如果是空樹,則返回0
}

void PrintTree(BitTree Boot,int nLayer)  //按豎向樹狀打印的二叉樹 //
{
    int i;
 if(Boot==NULL) return;
 PrintTree(Boot->RChild,nLayer+1);
 for(i=0;i<nLayer;i++)
  printf("  ");
 printf("%c\n",Boot->data);
 PrintTree(Boot->LChild,nLayer+1);
}
int main()
{
 BitTree T;
 int h;
 int layer;
 int treeleaf;
 layer=0;
 printf("請輸入二叉樹中的元素(以擴展先序遍歷序列輸入,其中#代表空子樹):\n");
    CreatBiTree(&T);
 printf("先序遍歷序列爲:");
 PreOrder(T);
 printf("\n");
 printf("中序遍歷序列爲:");
 InOrder(T);
 printf("\n");
 printf("後序遍歷序列爲:");
 PostOrder(T);
 printf("\n");
 h=PostTreeDepth(T);
 printf("The depth of this tree is:%d",h);
 printf("\n");
 PrintTree(T,layer);
 return 0; 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章