[二叉樹] 6.70 根據 廣義表GList 建立 二叉樹BiTree
阿新 • • 發佈:2018-12-13
題目來源:嚴蔚敏《資料結構》C語言版本習題冊 6.70
【題目】6.70 如果用大寫字母標識二叉樹結點,則一棵二叉樹可以用符合下面語法圖的字元序列表示。試寫一個遞迴演算法,由這種形式的字元序列,建立相應的二叉樹的二叉連結串列儲存結構
【思路】遞迴定義使用遞迴函式
【測試資料】A(B(#,D(#,#)),C(E(#,F(#,#)),#))
【答案】
// 6.70 由廣義表形式的輸入建立二叉連結串列
Status CreateBiTreeByGList(BiTree *pT) {
char c;
BiTNode *p;
c = getchar();
if (c=='#') p=NULL; //空子樹
else {
p = (BiTNode *)malloc(sizeof(BiTNode)); if (!p) exit(OVERFLOW);
p->data=c; //賦值
if (getchar()!='(') return ERROR; //格式錯誤
if ( !CreateBiTreeByGList( &p->lchild ) ) return ERROR; //建立左子樹
if (getchar()!=',') return ERROR; //格式錯誤
if ( !CreateBiTreeByGList( &p->rchild ) ) return ERROR; //建立右子樹
if (getchar()!=')') return ERROR; //格式錯誤
}
*pT = p; //把p傳出去
return TRUE;
}
【完整程式碼】
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#ifndef BASE
#define BASE
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int bool;
#endif
#define TElemType char //固定為char,若修改需要修改方法
typedef struct BiTNode { // 結點結構
TElemType data;
struct BiTNode *lchild, *rchild; // 左右孩子指標
}BiTNode, *BiTree;
void visit(TElemType e) {
printf("%c", e);
}
// 先序遍歷二叉樹
void PreOrder(BiTree T) { // - 遞迴
if (!T) return ;
visit(T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
// 中序遍歷二叉樹
void InOrder(BiTree T) { // - 遞迴
if (!T) return ;
InOrder(T->lchild);
visit(T->data);
InOrder(T->rchild);
}
// 後序遍歷二叉樹
void PostOrder(BiTree T) { // - 遞迴
if (!T) return ;
PostOrder(T->lchild);
PostOrder(T->rchild);
visit(T->data);
}
// 6.70 由廣義表形式的輸入建立二叉連結串列
Status CreateBiTreeByGList(BiTree *pT) {
char c;
BiTNode *p;
c = getchar();
if (c=='#') p=NULL; //空子樹
else {
p = (BiTNode *)malloc(sizeof(BiTNode)); if (!p) exit(OVERFLOW);
p->data=c; //賦值
if (getchar()!='(') return ERROR; //格式錯誤
if ( !CreateBiTreeByGList( &p->lchild ) ) return ERROR; //建立左子樹
if (getchar()!=',') return ERROR; //格式錯誤
if ( !CreateBiTreeByGList( &p->rchild ) ) return ERROR; //建立右子樹
if (getchar()!=')') return ERROR; //格式錯誤
}
*pT = p; //把p傳出去
return TRUE;
}
int main() {
/* 6.70測試資料
A(B(#,D(#,#)),C(E(#,F(#,#)),#))
*/
BiTree T;
int cnt;
cnt = CreateBiTreeByGList(&T);
if (cnt) {
printf("二叉連結串列:\n");
PreOrder(T);printf("\n");
InOrder(T);printf("\n");
PostOrder(T);printf("\n");
} else {
printf("輸入不規範\n");
}
return 0;
}