pat 甲级 1086(二叉树)

本文探讨了利用中序遍历信息逆序构建二叉树,并实现后序遍历的过程。通过详细的代码解析,展示了如何使用数组和堆栈进行节点的建立与返回,实现了对二叉树的有效遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

思路:就是输入中序建立的二叉树,要求输出后序遍历的二叉树,就是一个逆序建树的过程,

让我想了好久

注意:(1)可以用数组,但数组需要开的大一些,不然段错误

(2)对于堆栈,push就是建树,pop就是返回它的上一级。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cstring>
#include<stack>
using namespace std;
const int maxn = 9999999;
int a[maxn],tp,num;
vector <int> v;
void build(int x)
{
	if(num<=0) return ;
	string s;
	cin>>s;
	if(s[1]=='u')
	{
		cin>>tp;
		a[x]=tp;
		num--;
		build(x*2);
		build(x*2+1);
	}
	else num--;
}
void postorder(int x,vector <int> &vc)
{
	if(a[x])
	{
		postorder(x*2,vc);
		postorder(x*2+1,vc);
		vc.push_back(a[x]);
	}
}
int main(void)
{
	memset(a,0,sizeof(a));
	int x=1,n,i,j;
	cin>>n;
	num=n*2;
	build(1);
	//for(i=1;i<=n;i++) cout<<a[i]<<" ";
	v.clear();
	postorder(1,v);
	for(i=0;i<v.size()-1;i++) cout<<v[i]<<" ";
	cout<<v[i]<<endl; 
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值