二叉树 三种遍历构造二叉树+层次遍历 题目 PAT 树的遍历

https://www.patest.cn/contests/gplt/L2-006

1.后序遍历+中序遍历,构建二叉树。

2.队列层次输出二叉树

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<string>
using namespace std;
int n;
int in[35],post[35];
struct node
{
	int data;
	node* lchil;
	node* rchil;
}tree[35];
node* buildTree(int *in,int *post,int length)
{
	//终止条件 
	if(length==0)return NULL;
	
	//创建节点,最终返回得到root节点 
	node *root;
	root = new node();
	//后序遍历的最后一个节点,为根节点 
	root->data=*(post+length-1);
	
	//pos中序遍历中找到与后序根节点相同的元素的下标 
	int pos=0;
	while(in[pos]!=post[length-1])
	pos++;
	//递归建树
	//格式(中序序列,后序序列,截断后长度) 
	root->lchil=buildTree(in,post,pos);
	root->rchil=buildTree(in+pos+1,post+pos,length-pos-1);
	
	return root;
}
void show(node *t)
{
	queue<node*>q;
	q.push(t);
	int flag=0;
	while(!q.empty())
	{
		node* tmp=q.front();
		q.pop();
		if(!flag)
		{
			cout<<tmp->data;
			flag=1;
		}
		else 
		cout<<' '<<tmp->data;
		
		if(tmp->lchil!=NULL)
		q.push(tmp->lchil);
		if(tmp->rchil!=NULL)
		q.push(tmp->rchil);
	}
	cout<<endl;
}
int main()
{
	while(cin>>n)
	{
		for(int i=0;i<n;++i)
		cin>>post[i];
		for(int i=0;i<n;++i)
		cin>>in[i];
		//1. 
		//构造二叉树 保存到root节点 
		//in是中序序列
		//post是后序序列
		//n是两种序列长度 
		node* root=buildTree(in,post,n); 
		//2.
		//遍历bfs获得层次序列 
		show(root);
	}
}

//前序遍历 
void show(node* t)
{
	if(t!=NULL)
	{
		cout<<t->data<<' ';
		show(t->lchil);	
		show(t->rchil);
	}
}
//中序遍历 
void show(node* t)
{
	if(t!=NULL)
	{
		show(t->lchil);	
		cout<<t->data<<' ';
		show(t->rchil);
	}
}
//后序遍历 
void show(node* t)
{
	if(t!=NULL)
	{
		show(t->lchil);	
		show(t->rchil);
		cout<<t->data<<' ';
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值