C语言中树的建立和遍历

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

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


前序遍历:ABDECF。

中序遍历:DBEACF。

后序遍历:DEBFCA。

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

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

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

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;
}
输入与结果为:

  • 11
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值