【二叉树】建立 | 先序遍历 | 中序遍历 | 后序遍历 | 层次遍历

#include<cstdio>
#include<stdlib.h> 
#include<queue>

using namespace std;

typedef struct Node
{
	char data;
	Node *left;
	Node *right;
}node; //指typdef struct Node node
//结构体定义新变量时必须struct+结构体名,上述语句让struct Node有个别名node 
 
//先序建立二叉树 
node* createT()
{
	node *root;
	char ch = getchar();
	if(ch=='#') root = NULL; //'#'指空子树 
	else
	{
		root = new node;
		root->data = ch;
		root->left = createT();
		root->right = createT();
	}
	return root;
}

//先序遍历 
void preOrder(node *T)
{
	if(T==NULL) return;
	printf("%c ",T->data);
	preOrder(T->left);
	preOrder(T->right);
}

//中序遍历 
void inOrder(node *T)
{
	if(T==NULL) return;
	inOrder(T->left);
	printf("%c ",T->data);
	inOrder(T->right);
}

//后序遍历 
void postOrder(node *T)
{
	if(T==NULL) return;
	postOrder(T->left);
	postOrder(T->right);
	printf("%c ",T->data);
}

//层次遍历 
void layerOrder(node *T)
{
	//队列是node*而不是node
	queue<node*> q;
	q.push(T); //根元素入队 
	while(!q.empty())
	{
		node* top = q.front(); //取出队首元素 
		q.pop();  
		printf("%c ",top->data);
		if(top->left) q.push(top->left); //左子树非空 
		if(top->right) q.push(top->right); //右子树非空 
	}
	//无论是遍历还是建立,都不要忘了子树空不空的问题 
}

int main()
{
	node *T;
	T = createT();
	printf("先序遍历:");
	preOrder(T);
	printf("\n中序遍历:");
	inOrder(T);
	printf("\n后序遍历:");
	postOrder(T);
	printf("\n层次遍历:");
	layerOrder(T);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值