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 PopSample Output:
3 4 2 6 5 1
思路
在1020的基础上稍微增加了难度。
1.仔细观察发现这道题中栈的压入操作其实是树的前序遍历,弹出操作是树的中序遍历
2.那么可以根据输入操作的不同构造出树的前序序列和中序序列,由此转化为类似pat1020 的问题了。
代码
#include<iostream> #include<vector> using namespace std; vector<int> preorder(31); vector<int> inorder(31); vector<int> mypostorder(31); int index = 1; void postorder(int pfirst,int plast,int ifirst,int ilast ) { if(pfirst > plast || ifirst > ilast) return; int i = 0; while(preorder[pfirst] != inorder[ifirst + i]) i++; //find root's index in inorder sequence postorder(pfirst + 1,pfirst + i,ifirst,ifirst + i); postorder(pfirst + i + 1,plast,ifirst + i + 1,ilast); mypostorder[index++] = preorder[pfirst]; } int main() { int N; while(cin >> N) { vector<int> stk; int in = 1,out = 1; //input while(in <= N || out <= N) { string command; int value; cin >> command ; if(command[1] == 'u') { cin >> value; preorder[in++] = value; stk.push_back(value); } else { inorder[out++] = stk.back(); stk.pop_back(); } } //handle postorder(1,N ,1,N); //output int j = 1; cout << mypostorder[j]; for(int j = 2;j <= N;j++) cout <<" " << mypostorder[j]; cout << endl; } }