二叉樹的建立與訪問演算法的設計(三種遍歷方法)
阿新 • • 發佈:2018-12-22
二叉樹的建立與訪問演算法的設計(三種遍歷方法)
1、【問題描述】
從鍵盤輸入二叉樹的元素,建立二叉樹,實現二叉樹的遍歷演算法。
【基本要求】
實現以下基本操作:
(1)從鍵盤輸入二叉樹的元素,建立二叉樹。
(2)實現二叉樹的先序遍歷演算法。
2、【問題描述】
從鍵盤輸入二叉樹的元素,建立二叉樹,實現二叉樹的遍歷演算法。
【基本要求】
實現以下基本操作:
(1)從鍵盤輸入二叉樹的元素,建立二叉樹。
(2)實現二叉樹的中序遍歷演算法。
3、【問題描述】
從鍵盤輸入二叉樹的元素,建立二叉樹,實現二叉樹的遍歷演算法。
【基本要求】
實現以下基本操作:
(1)從鍵盤輸入二叉樹的元素,建立二叉樹。
(2)實現二叉樹的後序遍歷演算法。
程式
#include<stdio.h> #include<malloc.h> #include<stdlib.h> typedef struct tree{ char date; struct tree *lchild; struct tree *rcjild; }tree,*shu; shu xjl(){ char b; shu p; scanf("%c",&b); if(b=='$'){ p=NULL; } else{ p=(shu)malloc(sizeof(tree)); p->date=b; p->lchild=xjl(); p->rcjild=xjl(); } return p; } void xbl( shu p ){ if(p!=NULL){ printf("%c\n",p->date); xbl(p->lchild); xbl(p->rcjild); } } shu zjl(){ char b; shu t; scanf("%c",&b); if(b=='$'){ t=NULL; } else{ t=(shu)malloc(sizeof(tree)); t->lchild=zjl(); t->date=b; t->rcjild=zjl(); } return t; } void zbl( shu t ){ if(t!=NULL){ zbl(t->lchild); printf("%c\n",t->date); zbl(t->rcjild); } } shu hjl(){ char b; shu f; scanf("%c",&b); if(b=='$'){ f=NULL; } else{ f=(shu)malloc(sizeof(tree)); f->lchild=hjl(); f->date=b; f->rcjild=hjl(); } return f; } void hbl( shu f ){ if(f!=NULL){ hbl(f->lchild); hbl(f->rcjild); printf("%c\n",f->date); } } void cd(){ int n; shu f; shu t; shu p; printf("***************************\n"); printf(" 請選擇你要執行的功能:\n\n" ); printf(" 1、先序遍歷建立二叉樹\n\n"); printf(" 2、中序遍歷建立二叉樹\n\n"); printf(" 3、後序遍歷建立二叉樹\n\n"); printf(" 4、退出\n\n"); printf(" 5、返回主選單\n\n"); printf("***************************\n"); scanf("%d",&n); getchar(); switch(n){ case 1: printf("請輸入建立先序遍歷二叉樹資料:\n"); printf("----------------------------\n"); p=xjl(); printf("----------------------------\n"); printf("輸出的先序遍歷為:\n"); printf("----------------------------\n"); xbl(p); printf("----------------------------\n"); break; case 2: printf("請輸入建立中序遍歷二叉樹資料:\n"); printf("-----------------------------\n"); p=zjl(); printf("-----------------------------\n"); printf("輸出的中序遍歷為:\n"); printf("-----------------------------\n"); zbl(t); printf("-----------------------------\n"); break; case 3: printf("請輸入建立中序遍歷二叉樹資料:"); printf("-----------------------------\n"); p=hjl(); printf("-----------------------------\n"); printf("輸出的後序遍歷為:\n"); printf("-----------------------------\n"); hbl(f); printf("-----------------------------\n"); break; case 4: break; case 5: cd(); break; } } int main(){ int n; shu p; shu t; shu f; cd(); return 0; }