7-5 Tree Traversals Again
7-5 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
本題我利用輸入資料得到前序和中序遍歷的結果然後進行建樹,對於有重複元素的樹的資料樣例不通過
本方法僅代表一種思路,歡迎有好的改進思路的人評論
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
int preorder[1000], inorder[1000]; //利用輸入得到前序和中序遍歷的結果
int j = 0, k = 0;
int tree[100000];
int output[10000];
int tp = 0;
void createTree(int pl,int pr,int il,int ir,int root) { //前中建樹
if (il == ir) {
tree[root] = inorder[il];
return;
}
tree[root] = preorder[pl];
int llen, rlen, k;
for (int i = il; i <= ir; i++)
if (inorder[i] == preorder[pl]) k = i;
llen = k - il;
rlen = ir - k;
if (llen > 0) createTree(pl+1,pl+llen,il,k-1,root*2);
if (rlen > 0)createTree(pl + llen + 1, pr, k + 1, ir, root * 2 + 1);
return ;
}
void PostorderTraversal(int r) { //後序遍歷
if (tree[2 * r] != -1) PostorderTraversal(2 * r);
if (tree[2 * r+1] != -1) PostorderTraversal(2 * r+1);
output[tp++] = tree[r];
return;
}
int main() {
int n = 0;
cin >> n;
if (n < 1) return 0 ;
stack<int> sta;
for (int i = 0; i < 2 * n; i++) {
string s;
cin >> s;
int t;
if (s == "Push") {
cin >> t;
sta.push(t);
preorder[j++] = t; //前序遍歷
}
else if (s == "Pop"&&!sta.empty()) {
inorder[k++] = sta.top(); //中序遍歷
sta.pop();
}
}
for (int i = 0; i < 100000; i++)
tree[i] = -1;
createTree(0,n-1,0,n-1,1);
/* for (int i = 0; i < 1000; i++)
if (tree[i] != -1) cout << "i: " << i << " " << tree[i] << endl;*/
PostorderTraversal(1);
for (int i = 0; i < tp; i++) {
if (i == 0) cout << output[i];
else
cout <<" "<<output[i];
}
return 0;
}