A1086 Tree Traversals Again (25分)

一、技术总结

  1. 出现过段错误,答案错误,答案错误是空格输出,记得是小于n-1,而段错误是由于函数的参数问题,也有可能是输入时方式问题,string类型的如果用scanf可能会出现段错误,可以改用cin解决问题。
  2. 可以使用include<bits/stdc++.h>代替所有头文件
  3. 正常的二叉树操作,定义数据结构,遍历看是要求什么遍历函数,然后根据两种遍历进行创建二叉树函数。

二、参考代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 50;
struct Node{
	int data;
	Node* lchild;
	Node* rchild;
};
stack<int> s;
int in[maxn], pre[maxn];
int n, num = 0;
void PostOrder(Node* root){
	if(root == NULL){
		return;
	}
	PostOrder(root->lchild);
	PostOrder(root->rchild);
	printf("%d", root->data);
	if(num < n-1){
		printf(" ");
		num++;
	}
}
Node* create(int preL, int preR, int inL, int inR){
	if(preL > preR){
		return NULL;
	}
	Node* now = new Node;
	now->data = pre[preL];
	int k;
	for(k = 0; k < preR; k++){
		if(pre[preL] == in[k]){
			break;
		}
	}
	int numLeft = k - inL;
	now->lchild = create(preL+1, preL+numLeft, inL, k-1);//这里只能够是k-1,不用加上inL
	now->rchild = create(preL+numLeft+1, preR, k+1, inR);
	return now;
}
int main(){
	scanf("%d", &n);
	int num1 = 0, num2 = 0;
	//char str[5];
	string str;
	for(int i = 0; i < 2*n; i++){
		cin >> str;
		if(str.compare("Push") == 0){
			int data1;
			scanf("%d", &data1);
			pre[num1++] = data1;
			s.push(data1);
		}else{
			in[num2++] = s.top();
			s.pop();
		}
	}
	Node* root = create(0, n-1, 0, n-1);
	PostOrder(root);
	return 0;
}
posted @ 2020-02-15 21:07  睿晞  阅读(197)  评论(0编辑  收藏  举报