樹3 Tree Traversals Again (中國大學MOOC-陳越、何欽銘-資料結構-2018秋)
03-樹3 Tree Traversals Again (25 point(s))
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<stdio.h>
#include<string>
#include<sstream>
#include<vector>
#include<stack>
using namespace std;
int N, cur=0;
vector<int>preorder;
vector<int>inorder;
typedef struct TreeNode *Node;
struct TreeNode
{
int num;
Node left;
Node right;
TreeNode() {
left = NULL;
right = NULL;
}
};
int findrootindex(int rootnum)
{
for (int i = 0; i < N; i++)
{
if (inorder[i]==rootnum)
{
return i;
}
}
return -1;
}
Node createtree(int left, int right) {
if (left>right)
{
return NULL;
}
int root = preorder[cur];
cur++;
int rootindex = findrootindex(root);
Node T = new TreeNode();
T->num = root;
if (left!=right)
{
T->left = createtree(left, rootindex-1);
T->right = createtree(rootindex + 1, right);
}
return T;
}
bool FLAG = true;
void postfix(Node T)
{
if (!T)
{
return;
}
postfix(T->left);
postfix(T->right);
if (FLAG)
{
cout << T->num;
FLAG = false;
}
else
{
cout <<' '<<T->num;
}
}
int main()
{
stringstream ss;
string INPUT,Nstr;
getline(cin, Nstr);
ss << Nstr;
ss >> N;
ss.clear();
stack<int>stk;
int value;
for (int i = 0; i <N*2; i++)
{
getline(cin, INPUT);
if (INPUT[1]=='u')
{
string num = INPUT.substr(5);
ss << num;
ss >> value;
ss.clear();
stk.push(value);
preorder.push_back(value);
}
else
{
value = stk.top();
stk.pop();
inorder.push_back(value);
}
}
Node T =createtree(0,N-1) ;
postfix(T);
return 0;
}