浙大数据结构 玩转二叉链表

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;
}

猜你喜欢

转载自blog.csdn.net/red_red_red/article/details/83755818