【PAT甲级】1086 Tree Traversals Again (25分)

解题过程的小记录,如有错误欢迎指出。

难度:四星(给出先序和中序求后序,数据的读取是难点)

题目分析

给出先序数列和中序数列,要求输出后序数列(push进去的顺序是先序,利用栈pop出来的顺序是中序)

注意点

要通过先序、后序、中序中其中几个get到二叉树的结构,必须要有中序

我的解题过程

思路

本题的基本思路和上一题一致,难点在于如何通过给出的Push和Pop语句读取到数据

  1. 先读入一个string(string以空格判断结尾)
  2. 然后判断这个string是Push还是Pop,如果是Push的话紧跟着再读入一个数据data,插入进先序数列并入栈,如果是Pop,就出栈并且插入中序数列
  3. 读取了先序和中序数列后的操作就非常常规了

bug

刚开始用getline获取一行Pop或者Push,然后直接读取读到的string[index]来转换为num,这样只能用作一位数,如果是多位数的话emm也可以用substr进行解决吧,但还是采用再读入一个int比较方便一些

代码

#include<iostream>
#include<stack>
#include<string>

using namespace std;

int pre[35], in[35], n, cnt = 0;

struct node {
	int data;
	node *lchild, *rchild;
};

node* create(int preL, int preR, int inL, int inR) {
	if (preL > preR) return NULL;
	node *root = new node;
	root->data = pre[preL];
	int i = inL;
	for (i; i <= inR; i++) {
		if (in[i] == pre[preL]) break;
	}
	int numLeft = i - inL;
	root->lchild = create(preL + 1, preL + numLeft, inL, i - 1);
	root->rchild = create(preL + numLeft + 1, preR, i + 1, inR);
	return root;
}

void postorder(node *root) {
	if (root == NULL) return;
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%d", root->data);
	cnt++;
	if (cnt != n) printf(" ");
}

int main()
{
	scanf("%d\n", &n);
	stack<int> temp;
	int preindex = 0, inindex = 0;
	for (int i = 0; i < 2 * n; i++) {
		string s;
		cin >> s;
		if (s[1] == 'u') {//Push
			int num;
			cin >> num;
			temp.push(num);
			pre[preindex++] = num;
		}
		else {//Pop
			int num = temp.top();
			temp.pop();
			in[inindex++] = num;
		}
	}
	node *root = create(0, n - 1, 0, n - 1);
	postorder(root);
    return 0;
}

dalao的代码

全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~

借鉴点

本题代码参考自己和晴神的即可(基本一致)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值