浙大數據結構 玩轉二叉鏈表

7-20 玩轉二叉鏈表 (20 分)

設計程序,按先序創建二叉樹的二叉鏈表;然後先序、中序、後序遍歷二叉樹。

輸入格式:

按先序輸入一棵二叉樹。二叉樹中每個結點的鍵值用字符表示,字符之間不含空格。注意空樹信息也要提供,以#字符表示空樹。

輸出格式:

輸出3行。第一行是先序遍歷二叉樹的序列,第二行是中序遍歷二叉樹的序列,第三行是後序遍歷二叉樹的序列。每行首尾不得有多餘空格。序列中不含#。

輸入樣例:

ab##dc###

輸出樣例:

abdc
bacd
bcda

 

#include <stdio.h>
#include <stdlib.h>
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode {
	ElementType Data;
	BinTree Left;
	BinTree Right;
};
BinTree CreatBinTree() {//先序建立二叉鏈表
	BinTree B;
	char cp;
	scanf("%c",&cp);
	if(cp=='#'){
		B=(BinTree)malloc(sizeof(struct TNode));
		//B=NULL;
		B->Data='#';
		B->Left=B->Right=NULL;
	}
		
	else {
		B=(BinTree)malloc(sizeof(struct TNode));
		B->Data =cp;
		B->Left =CreatBinTree();
		B->Right=CreatBinTree();
	}
	return B;
}
void PreorderPrintLeaves1( BinTree BT ) {//先
	if(BT->Data !='#') {
		printf("%c",BT->Data );
		PreorderPrintLeaves1( BT->Left  );
		PreorderPrintLeaves1( BT->Right  );
	}
}
void PreorderPrintLeaves2( BinTree BT ) {//中
	if(BT->Data !='#') {
		PreorderPrintLeaves2( BT->Left  );
		printf("%c",BT->Data );
		PreorderPrintLeaves2( BT->Right  );
	}
}
void PreorderPrintLeaves3( BinTree BT ) {//後
	if(BT->Data !='#') {
		PreorderPrintLeaves3( BT->Left  );
		PreorderPrintLeaves3( BT->Right  );
		printf("%c",BT->Data );
	}
}
int main() {
	BinTree BT = CreatBinTree();
	PreorderPrintLeaves1(BT);
	printf("\n");
	PreorderPrintLeaves2(BT);
	printf("\n");
	PreorderPrintLeaves3(BT);
	printf("\n");
	return 0;
}

 

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