實驗2.1:二叉樹的先序建立、先序遍歷、中序遍歷、後序遍歷
阿新 • • 發佈:2019-02-11
題目:參照程式5.1~5.4,編寫程式,完成二叉樹的先序建立、先序遍歷、中序遍歷、後序遍歷等操作。
部分程式碼:
二叉樹結構體定義:
typedef struct BinaryTreeNode{
T Data;
struct BinaryTreeNode *LChild, *RChild;
}BinaryTreeNode;
先序遍歷構建二叉樹:
//先序遍歷構建二叉樹 BinaryTreeNode *PreCreateBt(BinaryTreeNode *t){ char ch; ch = getchar(); if(ch == '#'){ //輸入為#表示這裡建立空二叉樹,即遍歷演算法的空操作 t = NULL; } else{ t = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode)); t->Data = ch; //構造根結點 t->LChild = PreCreateBt(t->LChild); //構造左子樹 t->RChild = PreCreateBt(t->RChild); //構造右子樹 } return t; }
先序遍歷:
//先序遍歷
void PreOrderTransverse(BinaryTreeNode *t){
if(t==NULL){
return;
}
printf("%c",t->Data); //列印輸出根結點,此處可以定義其他操作
PreOrderTransverse(t->LChild); //然後先序遍歷左子樹
PreOrderTransverse(t->RChild); //最後先序遍歷右子樹
}
中序遍歷:
//中序遍歷 void InOrderTransverse(BinaryTreeNode *t){ if(t==NULL){ return; } InOrderTransverse(t->LChild); //中序遍歷根結點的左子樹 printf("%c",t->Data); //列印輸出根結點,此處可以定義其他操作 InOrderTransverse(t->RChild); //最後中序遍歷根結點的右子樹 }
後序遍歷:
//後序遍歷
void PostOrderTransverse(BinaryTreeNode *t){
if(t==NULL){
return;
}
PostOrderTransverse(t->LChild); //後序遍歷根結點的左子樹
PostOrderTransverse(t->RChild); //然後後序遍歷根結點的右子樹
printf("%c",t->Data); //最後列印輸出根結點,此處可以定義其他操作
}
完整程式:
#include<stdio.h> #include<stdlib.h> typedef char T; typedef struct BinaryTreeNode{ T Data; struct BinaryTreeNode *LChild, *RChild; }BinaryTreeNode; //先序遍歷 void PreOrderTransverse(BinaryTreeNode *t){ if(t==NULL){ return; } printf("%c",t->Data); //列印輸出根結點,此處可以定義其他操作 PreOrderTransverse(t->LChild); //然後先序遍歷左子樹 PreOrderTransverse(t->RChild); //最後先序遍歷右子樹 } //中序遍歷 void InOrderTransverse(BinaryTreeNode *t){ if(t==NULL){ return; } InOrderTransverse(t->LChild); //中序遍歷根結點的左子樹 printf("%c",t->Data); //列印輸出根結點,此處可以定義其他操作 InOrderTransverse(t->RChild); //最後中序遍歷根結點的右子樹 } //後序遍歷 void PostOrderTransverse(BinaryTreeNode *t){ if(t==NULL){ return; } PostOrderTransverse(t->LChild); //後序遍歷根結點的左子樹 PostOrderTransverse(t->RChild); //然後後序遍歷根結點的右子樹 printf("%c",t->Data); //最後列印輸出根結點,此處可以定義其他操作 } //先序遍歷構建二叉樹 BinaryTreeNode *PreCreateBt(BinaryTreeNode *t){ char ch; ch = getchar(); if(ch == '#'){ //輸入為#表示這裡建立空二叉樹,即遍歷演算法的空操作 t = NULL; } else{ t = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode)); t->Data = ch; //構造根結點 t->LChild = PreCreateBt(t->LChild); //構造左子樹 t->RChild = PreCreateBt(t->RChild); //構造右子樹 } return t; } int main(){ BinaryTreeNode *t = NULL; t = PreCreateBt(t); //有返回值,所以前面要加個t = ,不然後面沒東西輸出 printf("\nPreOrderTransverse:\n"); PreOrderTransverse(t); printf("\n\nInOrderTransverse:\n"); InOrderTransverse(t); printf("\n\nPostOrderTransverse:\n"); PostOrderTransverse(t); printf("\n"); return 0; }
實驗結果:輸入ABEH###C#D##MN###