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

一、题目分析

1. 翻译

binary tree:二叉树
inorder:中序
preorder:前序
postorder:后序
traversal / traverse:遍历
non-recursive:非递归

2. 关键点

1)入栈顺序为前序序列,出栈顺序为中序序列,已知前序、中序序列,可以唯一地确定一棵树,输出其后序序列。
2)输出的序列最后一个数字后面没有空格。

二、代码解析

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <cctype>
#include <stack>
#include <unordered_map>
using namespace std;
struct bnode {
	int data;
	struct bnode *lchild,*rchild;
};
int n,k=0;//n是结点总数,k用来规范输出格式 

bnode* create(int pre[],int in[],int preL,int preR,int inL,int inR) {//左右闭区间
	if(preL>preR) return NULL;
	int i;
	bnode* root=new bnode;
	root->data=pre[preL];
	for(i=inL; i<=inR; i++) {
		if(root->data==in[i]) {
			break;
		}
	}
	int leftnum=i-inL;
	root->lchild=create(pre,in,preL+1,preL+leftnum,inL,i-1);
	root->rchild=create(pre,in,preL+leftnum+1,preR,i+1,inR);
	return root;
}
void postorder(bnode* root){
	if(root==NULL){
		return;//不是要函数返回具体的值,而是结束递归 
	}
	postorder(root->lchild);
	postorder(root->rchild);
	k++;
	if(k!=n) printf("%d ",root->data);
	else printf("%d",root->data);
}

int main() {
	scanf("%d",&n);
	bnode node[n];
	string temp;
	stack<int> inorder;//stack的使用
	int pre[n],in[n],post[n],p=0,u=0,j=1;
	for(int i=0; i<n*2; i++) {
		cin>>temp;
		int num;
		if(temp=="Push") {
//			第一次提交的代码:
//			cin>>pre[p++];
//			inorder.push(j++);
//			第二次提交的代码:
			cin>>num;
			pre[p++]=num;
			inorder.push(num);
		} else {
			in[u++]=inorder.top();
			inorder.pop();
		}
	}//得到先序序列pre和中序序列in

	bnode* root=create(pre,in,0,n-1,0,n-1);
	postorder(root);

	return 0;
}

三、我的疑问

第一次的提交结果:
在这里插入图片描述第二次的提交结果:
在这里插入图片描述
第一次提交的代码是:

cin>>pre[p++];
inorder.push(j++);

第二次提交的代码是:

cin>>num;
pre[p++]=num;
inorder.push(num);

完全就是蒙出来的Σ(っ °Д °;)っ为什么会这样呀!?

如果喜欢我的博客,欢迎点赞、评论、收藏~~谢谢
( * ^ ▽ ^ * ) ~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值