二叉树,多元树的建立和遍历

 

 

多元树没有中序遍历

在建立多元树的时候因为不知道每个结点,有多少个儿子,所以比较麻烦。

这里使用了孩子兄弟法。

就是将二叉树的左右儿子指针,指向逻辑大儿子和第一个兄弟,而后便成了二叉树。

 

#include<stdio.h>
#include<string.h>
struct tree
{
	int node;
	tree * firstson;
	tree * nextbrother;
};
void buildtree(tree *&root) //先序建立多元树 
{
	int ch;
	scanf("%d",&ch);
	if(ch==0)
	{
		root=NULL;
		return ;
	}
		root=new tree;  //申请空间 
		root->node=ch;
		buildtree(root->firstson);   //遍历逻辑大儿子 
		buildtree(root->nextbrother);  //遍历兄弟 
}
void Preordertree(tree *root)  //先序遍历 
{  //根->大儿子树先序遍历->二儿子树先序遍历->...->n儿子树先序遍历 
	if(root==NULL)
	return;
    printf("%d ",root->node);   
	Preordertree(root->firstson); //遍历逻辑大儿子 
	Preordertree(root->nextbrother); //遍历兄弟 
}
void Postordertree(tree *root) //后序遍历 
{ //大儿子后序遍历->根->二儿子后序遍历->...->n儿子后序遍历 
	if(root==NULL)
	return;
	Postordertree(root->firstson);	//遍历逻辑大儿子 
	printf("%d ",root->node);
	Postordertree(root->nextbrother); //遍历兄弟 

}
int main()
{
	tree *root;
	printf("先序建立多元树\n"); 
	buildtree(root);
	printf("先序遍历:\n");
	Preordertree(root);
	printf("\n后序遍历:\n");
	Postordertree(root);
	printf("\n");
}

 

 

二叉树

 

#include<stdio.h>
#include<string.h>
struct tree
{
	int node;
	tree *left;
	tree *right;
};
void buildtree(tree *&root) //先序建立二叉树 
{  
	int ch;
	scanf("%d",&ch);
	if(ch==0)
	{
		root=NULL;
		return;
	}
	root=new tree;   //申请空间 
	root->node=ch;
	buildtree(root->left);  //建立左儿子 
	buildtree(root->right); //建立右儿子 
}
void Preordertree(tree *root)  //先序遍历 
{//根->左->右 
	if(root==NULL)
	return;
	printf("%d ",root->node); //输出根 
	Preordertree(root->left); //遍历左儿子 
	Preordertree(root->right);//遍历右儿子 
}
void Inordertree(tree *root) //中序遍历 
{ //左->根->右 
	if(root==NULL)
	return;
	Inordertree(root->left);
	printf("%d ",root->node);
	Inordertree(root->right);
}
void Postordertree(tree *root) //后序遍历 
{ //左->右->根 
	if(root==NULL)
	return;
	Postordertree(root->left);
	Postordertree(root->right);
	printf("%d ",root->node);
}
int main()
{
	tree *root;
	printf("先序输入二叉树:\n");
	buildtree(root);
	printf("\n先序遍厉:\n");
	Preordertree(root);
	printf("\n中序遍历:\n");
	Inordertree(root);
	printf("\n后序遍历:\n");
	Postordertree(root); 
}

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值