中国大学MOOC-陈越、何钦铭-数据结构-2018秋 03-树3 Tree Traversals Again (25 分)

#include "pch.h"
#include 

#include 
#include 

using namespace std;

int preorder[35], inorder[35];
int pre_index = 0, in_index = 0, N, cnt = 0;

int get();
void build(int pre_begin, int pre_end, int in_begin, int in_end);
int main()
{
	cin >> N;
	stack sta;
	for (int i = 0; i < 2 * N; i++) {

		int tmp = get();

		if (tmp != -1) {

			sta.push(tmp);
			preorder[pre_index++] = tmp;

		}
		else {

			inorder[in_index++] = sta.top();
			sta.pop();

		}
	}

	build(0, N - 1, 0, N - 1);
	return 0;
}

int get()
{
	int tmp;
	string s;
	
	cin >> s;

	if (s[1] == 'o') return -1;
	cin >> tmp;
	return tmp;
}

void build(int pre_begin, int pre_end, int in_begin, int in_end)
{
	if (pre_begin > pre_end) return;

	int root = preorder[pre_begin];
	int in_root = in_begin;

	while (inorder[in_root] != root) in_root++;

	build(pre_begin + 1, pre_begin + in_root - in_begin, in_begin, in_root - 1);
	build(pre_begin + in_root - in_begin + 1, pre_end, in_root + 1, in_end);

	if (cnt++ != 0) putchar(' ');
	cout << root;
}
Download as text 

你可能感兴趣的:(PTA)