二叉树的创建+先序、中序,后序遍历

#include
#include

typedef char ElemType;
typedef struct BTNode
{
	ElemType data;
	struct BTNode *left;
	struct BTNode *right;
}BTNode;

//创建二叉树
void createBTNode(BTNode *&BT)
{
	ElemType ch;
	scanf("%c",&ch);
	if(ch==' ')
		BT=NULL;
	else
	{
		BT = (BTNode*)malloc(sizeof(BTNode));
		BT->data= ch;
		createBTNode(BT->left);
		createBTNode(BT->right);
	}
}

//先序遍历二叉树
void printDLR(BTNode *BT)
{
	if(BT)
	{
		printf("%c ",BT->data);
		printDLR(BT->left);
		printDLR(BT->right);
	}
}

//中序遍历二叉树
void printLDR(BTNode *BT)
{
	if(BT)
	{
		printLDR(BT->left);
		printf("%c ",BT->data);
		printLDR(BT->right);
	}
}

//后序遍历二叉树
void printLRD(BTNode *BT)
{
	if(BT)
	{
		printLRD(BT->left);
		printLRD(BT->right);
		printf("%c ",BT->data);
	}
}

void main()
{
	BTNode *BT;
	createBTNode(BT);
	printf("先序遍历:");
	printDLR(BT);
	printf("\n");
	printf("中序遍历:");
	printLDR(BT);
	printf("\n");
	printf("后序遍历:");
	printLRD(BT);
	printf("\n");
}

输入时:按照先序遍历的方式依次输入结点,如果孩子结点为空时则输入空格。 

如输入:ABD  E  CF

得到的:

先序遍历:A B D E C F

中序遍历:D B E A F C

后序遍历:D E B F C A

你可能感兴趣的:(树,链表,c语言,二叉树)