C语言中树的建立和遍历

树的遍历分为三种:前序遍历(根左右),中序遍历(左根右),后序遍历(左右根)。

PS:根左右,就是先遍历根节点,然后是左子树,最后是右子树。如下图:

C语言中树的建立和遍历_第1张图片

前序遍历:ABDECF。

中序遍历:DBEACF。

后序遍历:DEBFCA。

PPS:有一种更便捷的方法来写出三种遍历的结果:从根节点开始,从左面画线,将树沿着边界圈起来。按照线在节点的不同位置依次写出数据。其中:前序遍历为线在节点左侧;中序遍历为线在节点下方;后序遍历为线在节点右侧。如下图:C语言中树的建立和遍历_第2张图片

这里我们用前序遍历的方法来建立树。使其输出三种遍历的结果:

#include 
#include 

struct node{//建立节点
	char data;
	struct node* left;
	struct node* right;
};
//前序遍历
void pre_order(struct node* root)
{
	if(root == NULL)
		return ;
	else {
		printf("%c\t", root->data);
		pre_order(root->left);
		pre_order(root->right);
	}
}
//中序遍历
void min_order(struct node* root)
{
	if(root == NULL)
		return ;
	else {
		min_order(root->left);
		printf("%c\t", root->data);
		min_order(root->right);
	}
}
//后序遍历
void postorder(struct node* root)
{
	if(root == NULL)
		return ;
	else {
		postorder(root->left);
		postorder(root->right);
		printf("%c\t", root->data);
	}
}
//前序遍历创建树
struct node* create(struct node* root)
{
	char ch = getchar();	//没有子树的用#表示
	if(ch == '#')
		return NULL;
	else {
		root = malloc(sizeof(struct node));
		root->data = ch;
		root->left = create(root->left);
		root->right = create(root->right);
		return root;
	}
}

int main()
{
	struct node* root = NULL;

	root = create(root);

	pre_order(root);
	printf("\n");
	min_order(root);
	printf("\n");
	postorder(root);
	printf("\n");

	return 0;
}
输入与结果为:
 
 

你可能感兴趣的:(C知识点)