Binary Tree Traversals(ACM训练 - 对顶堆学习笔记)
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
input
The input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.
output
For each test case print a single line specifying the corresponding postorder sequence.
Sample Input
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1
当数据大于小堆max时读入小堆否则堆入大堆,当小堆size大于大堆时,将小堆最大元素堆入大堆中,当大堆size大于小堆时,将大堆最小元素堆入小堆中;
很显然当大小堆差1时,其为中位数;
ac代码:
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> preorder;
vector<int> inorder;
stack<int> post;
int n;
void findtree(int preleft, int preright, int inleft, int inright) {
int i, j;
post.push(preorder[preleft]);
if (preleft == preright) return;
for (i = inleft; i <= inright; i++) {
if (preorder[preleft] == inorder[i]) break;
}
j = preleft + i - inleft + 1; //左右在pre分界点
if (j <= preright && i + 1 <= inright) {
findtree(j, preright, i + 1, inright);
}
if (preleft + 1 <= j - 1 && inleft <= i - 1) {
findtree(preleft + 1, j - 1, inleft, i - 1);
}
}
int main() {
while (cin >> n) {
int t;
preorder.clear();
inorder.clear();
for (int i = 0; i < n; i++) {
cin >> t;
preorder.push_back(t);
}
for (int i = 0; i < n; i++) {
cin >> t;
inorder.push_back(t);
}
findtree(0, n - 1, 0, n - 1);
//cout << post.size() << endl;
for (int i = 0; i < n; i++) {
cout << post.top();
post.pop();
if (!post.empty()) {
cout << " ";
}
}
cout << endl;
}
return 0;
}