03-树3 Tree Traversals Again

来源:互联网 发布:那的中超数据比较全 编辑:程序博客网 时间:2024/05/10 12:14

03-树3 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:

6Push 1Push 2Push 3PopPopPush 4PopPopPush 5Push 6PopPop

Sample Output:

3 4 2 6 5 1

#include<iostream>#include<string>#include<stack>using namespace std;int first=1;typedef struct Dnode{    int data;    struct Dnode *up;    struct Dnode *l;    struct Dnode *r;}Tree;void postOrderPrint(Tree *p){    if(p){        postOrderPrint(p->l);        postOrderPrint(p->r);        if(first){        cout<<p->data;        first=0;        }        else cout<<' '<<p->data;    }}int main(){    int n,num,lastOpea=0,cnt=0;    string s;    Tree *p=new Tree;    p->up=p->l=p->r=NULL;    cin>>n>>s>>p->data;    stack<int>points;    points.push(p->data);    while(cnt<n-1 && cin>>s){        if(s.compare("Push")==0){        cin>>num;        Tree *tem=new Tree;            tem->data=num;            tem->up=p;            while(1){            if(p->data==points.top()){                if(!lastOpea && !p->l){                    p=p->l=tem;                    break;                }                else if(lastOpea && !p->r){                    p=p->r=tem;                    points.pop();                    break;                }            }            else p=p->up;            }            points.push(num);            p->l=p->r=NULL;            cnt++;            lastOpea=0;        }        else{        if(lastOpea) points.pop();        lastOpea=1;        }    }    while(p->up) p=p->up;    postOrderPrint(p);    delete p;    return 0;}


原创粉丝点击