PAT1086:Tree Traversals Again
1086. Tree Traversals Again (25)
時間限制 200 ms 內存限制 65536 kB 代碼長度限制 16000 B 判題程序 Standard 作者 CHEN, YueAn 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
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; } }
PAT1086:Tree Traversals Again