时间限制
200 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
push 的顺序就是二叉树的前序
pop的顺序就是二叉树的中序遍历
本质上还是考根据这两个顺序建立二叉树,并且进行后序遍历
An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
Figure 1
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.
Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
6 Push 1 Push 2 Push 3 Pop Pop Push 4 Pop Pop Push 5 Push 6 Pop Pop
Sample Output:
3 4 2 6 5 1
来源: <http://www.patest.cn/contests/pat-a-practise/1086>
#include<iostream>
#include<vector>
#include<string>
#pragma warning(disable:4996)
using namespace std;
vector<int> s;
int inOrder[32] = { 0 },preOrder[32] = { 0 };
int n;
struct Node {
int val;
Node* left = NULL;
Node* right = NULL;
};
Node* BuildTree(int* pre, int* in, int n) {
if (n <= 0)
return NULL;
int i;
for (i = 0; i < n; i++) {
if (*(in + i) == *pre) {
break;
}
}
Node* p = (Node*)malloc(sizeof(Node));
p->val = *pre;
p->left = BuildTree(pre + 1, in, i);
p->right = BuildTree(pre + i + 1, in + i + 1, n - i - 1);
return p;
}
void PostOrder(Node *p) {
if (p->left != NULL)
PostOrder(p->left);
if (p->right != NULL)
PostOrder(p->right);
if (p->val != preOrder[0])
cout << p->val << " ";
else
cout << p->val;
}
int main(void) {
freopen("Text.txt", "r", stdin);
cin >> n;
string str;
for (int i = 0; i < 2 * n; i++) {
cin >> str;
if (str == "Push") {
int temp;
cin >> temp;
for (int j = 0; j < 31; j++) {
if (preOrder[j] == 0) {
preOrder[j] = temp;
break;
}
}
s.push_back(temp);
}
else {
for (int j = 0; j < 31; j++) {
if (inOrder[j] == 0) {
inOrder[j] = s[s.size() - 1];
break;
}
}
s.pop_back();
}
}
Node* root = (Node*)malloc(sizeof(Node));
root = BuildTree(preOrder, inOrder, n);
PostOrder(root);
return 0;
}