1. 程式人生 > >二叉樹的先序建立,先序遍歷、中序遍歷、後序遍歷、全部結點數、二叉樹深度、葉子結點數、二叉樹左右子樹交換

二叉樹的先序建立,先序遍歷、中序遍歷、後序遍歷、全部結點數、二叉樹深度、葉子結點數、二叉樹左右子樹交換

#include<stdlib.h>

#include<stdio.h>

#include<conio.h>
 typedef   char t;                          //定義資料型別
typedef struct BinaryTreeNode
{
    t  Data;
struct BinaryTreeNode *LChlid,*RChlid;
}BinaryTreeNode,* BinTree;                  //建立二叉樹鏈式儲存
BinaryTreeNode *PreCreateBt( )                    //先序建立二叉樹
{
    char ch;
BinTree t;
    ch=getchar();
    if(ch=='#')                   //輸入時用#表述為空
t=NULL;
    else{
        t = (BinTree *)malloc(sizeof(BinaryTreeNode));
        t->Data = ch;
        t->LChlid =PreCreateBt();
        t->RChlid =PreCreateBt();
    }
    return t;                                //返回根節點
}
void PreOrderTransverse(BinTree t)               //先序遍歷
{
if(t==NULL)
return;
printf("%c",t->Data);
PreOrderTransverse(t->LChlid);
PreOrderTransverse(t->RChlid);
   
}


void InOrderTransverse(BinTree t)                 //中序遍歷
{
if(t==NULL)
return;
else
{
InOrderTransverse(t->LChlid);
printf("%c",t->Data);
InOrderTransverse(t->RChlid);
}
}
void PostOrderTransverse(BinTree t)                //後序遍歷
{
if(t==NULL)
return;
PostOrderTransverse(t->LChlid);
PostOrderTransverse(t->RChlid);
    printf("%c",t->Data);
}
int Count(BinTree t)                              //全部結點個數
{
    if(t==NULL) 
        return 0;                     //空二叉樹結點數為0
    else                             //左右子樹結點總數加1
        return Count(t->LChlid)+Count(t->RChlid)+1;
}
int leafCount(BinTree t)             //葉子結點個數         
{
    if(t== NULL)
{
        return 0;
}
if ((t->LChlid==NULL) && (t->RChlid==NULL))
{
        return 1;
}
        return leafCount(t->LChlid)+leafCount(t->RChlid);
}
int High(BinTree t)                   //二叉樹深度
{  
int h;
    if(t==NULL)  
    h=0;
    else  
    {  
       int h1,h2;  
      h1= High(t->LChlid);  
       h2=High(t->RChlid,h2);
  if(h1>=h2)
  {
  h=h1;
  }
  else
  {
  h=h2;
  }
      h=h+1;   
    }  
return h;
}  
void SwapChildren(BinTree t)              //二叉樹交換左右子樹
{  
int temp;
    temp = (BinTree *)malloc(sizeof(BinaryTreeNode));
    if(t==NULL)
return;  
    temp = t->LChlid;  
    t->LChlid=t->RChlid;  
    t->RChlid = temp;  
  
    SwapChildren(t->LChlid);  
    SwapChildren(t->RChlid);  
printf("%c",t->Data);
}  
void main()
{
BinTree t; 
t=PreCreateBt();
printf("先序遍歷二叉樹:");              //功能性的介紹,可以去掉,不影響結果
   PreOrderTransverse(t);  
   printf("\n");  
   printf("中序遍歷二叉樹:");  
   InOrderTransverse(t);  
   printf("\n");  
   printf("後序遍歷二叉樹:");  
   PostOrderTransverse(t);  
   printf("\n");  
   printf("二叉樹結點總數:");
   printf("%d\n",Count(t));
   printf("葉子節點的個數:");
   printf("%d\n",leafCount(t));
   printf("樹的高度:%d\n",High(t)); 
   printf("二叉樹交換左右子樹:");
   SwapChildren(t);
   printf("\n");

比如建立最簡單的二叉樹根結點為B、左子樹為A、右子樹為C,運算結果如圖

輸入時要注意二叉樹建立的時候使用的是先序建立所以輸入的時候要保證使用先序輸入否則就會出錯