PAT甲级 A1086
题目详情
1086 Tree Traversals Again (25分)
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
解题思路
这道题就是通过中序和先序进行建树。需要注意树不能用数组,30个节点的可能情况太大了。只能用指针进行建树。建树的操作如下:
设置一个根节点。对于根节点,输入为前中序序列的号。找出其最大节点,进行左右的子树构造
以下为AC代码
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<algorithm>
#include<map>
#include<vector>
#include<iomanip>
#include<queue>
#include<cmath>
#include<stack>
using namespace std;
class Node {
public:
int value;
Node* left = NULL;
Node* right = NULL;
};
stack<int> temp;
vector<int> inorder;
vector<int> preorder;
int N;
Node* buildtree(int a1, int a2, int b1, int b2) {
if (a1 > a2) {
return NULL;
}
Node *rot = new Node();
rot->value = preorder[a1];
int inorderpos = 0;//分界线
for (int i = b1; i <= b2; i++) {
if (inorder[i] == preorder[a1]) {
inorderpos = i;
break;
}
}
int prepos = a1+(inorderpos-b1);//分界线
rot->left=buildtree(a1 + 1, prepos, b1, inorderpos - 1);
rot->right=buildtree( prepos + 1, a2, inorderpos + 1, b2);
return rot;
}
int cnt = 0;
void postPrint(Node* r) {
if (r == NULL) return;
postPrint(r->left);
postPrint(r->right);
if (cnt != 0) printf(" ");
if (cnt == 0) cnt = 1;
printf("%d", r->value);
}
int main() {
cin >> N;
for (int i = 0; i < 2 * N; i++) {
string s; cin >> s;
if (s == "Pop") {
int t = temp.top();
temp.pop();
inorder.push_back(t);
}
else {
int num; scanf_s("%d", &num);
preorder.push_back(num);
temp.push(num);
}
}
Node* root; root = NULL;
root=buildtree(0, preorder.size() - 1, 0, inorder.size() - 1);
postPrint(root);
}