二叉树的建立和四种遍历办法(前序,中序,后序,层次遍历)

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
typedef struct tree#二叉树的结构体
{
	char data;
	tree *left;
	tree *right;
}tree;
tree *creattree()#二叉树的建立
{
	tree *T;
	char a=getchar();
	if(a==' ')
	a=getchar();
	if(a=='*')
		return NULL;
	else
	{
	T=(tree *)malloc(sizeof(tree));
	T->data=a;
	T->left=creattree();
	T->right=creattree();
	return T;
	}
}
void preorder(tree *T)#前序遍历
{
	if(T)
	{
		printf("%c ",T->data);
		preorder(T->left);
		preorder(T->right);
	}
}
void inorder(tree *T)#中序遍历
{
	if(T)
	{
	inorder(T->left);
	printf("%c ",T->data);
	inorder(T->right);
	}
}
void lastorder(tree *T)#后序遍历
{
	if(T)
	{
	lastorder(T->left);
	lastorder(T->right);
	printf("%c ",T->data);
	}
}
void dfs(tree *T)#层次遍历
{
	queue<tree *> L;
	L.push(T);
	tree *s;
	while(!L.empty())
	{
		s=L.front();
		L.pop();
		printf("%c ",s->data);
		if(s->left)
		{
			L.push(s->left);
		}
		if(s->right)
		{
			L.push(s->right);
		}
	}
}
int main()
{
	tree *T=creattree();
	if(T==NULL)
		return 0;
	else{
	preorder(T);
	printf("\n");
	inorder(T);
	printf("\n");
	lastorder(T);
	printf("\n");
	dfs(T);
	return 0;
	}
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值