C语言-二叉树

#include<stdio.h>
#include<stdlib.h>

typedef struct BiTree {
	char data;
	struct BiTree *lchild;
	struct BiTree *rchild;
}BiTree,*BiNode;


//先序创建二叉树
BiNode create_tree() {
	BiTree *T;
	char a;
	scanf("%c", &a);
	if (a == '.')
		return NULL;//当输入 . 时表示这个节点为空,而且没有左右子树
	else {
		T = (BiNode)malloc(sizeof(BiTree));
		T->data = a;
		T->lchild = create_tree();
		T->rchild = create_tree();
	}

	return T;
}

//先序遍历
void pre_travel(BiNode root) {
	if (root) {
		printf("%c ", root->data);
		pre_travel(root->lchild);
		pre_travel(root->rchild);
	}
}

//中序遍历
void mid_travel(BiNode root) {
	if (root) {
		mid_travel(root->lchild);
		printf("%c ", root->data);
		mid_travel(root->rchild);
	}
}

//后序遍历
void post_travel(BiNode root) {
	if (root) {
		post_travel(root->lchild);
		post_travel(root->rchild);
		printf("%c ", root->data);
	}
}

int main() {
	BiNode root = create_tree();
	printf("先序遍历:");
	pre_travel(root);
	printf("\n");
	printf("中序遍历:");
	mid_travel(root);
	printf("\n");
	printf("后序遍历:");
	post_travel(root);
	printf("\n");

	system("pause");
	return 0;

}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页