前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >03-树3 Tree Traversals Again (25分)

03-树3 Tree Traversals Again (25分)

作者头像
AI那点小事
发布2020-04-20 16:29:56
4420
发布2020-04-20 16:29:56
举报
文章被收录于专栏:AI那点小事

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 NN (\le 30≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to NN). Then 2N2N 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


AC代码:

代码语言:javascript
复制
#include <iostream>
using namespace std;

struct Node{
    int tag;   //第几次进栈 
    int num;
};

/*先序遍历对应进栈顺序,中序遍历对应出栈顺序;  
  后序遍历与中序遍历不同的是节点出栈后要马上再入栈(tag做第二次入栈标记),等右儿子遍历完后再出栈;  
  具体实现上,每次中序遍历的pop时,如果栈顶是标记过的节点(tag=2),循环弹出;如果没有标记过(tag=1),做标记,即弹出再压栈)  
  栈顶tag=2的节点对应中序遍历中已弹出的节点;循环弹出后碰到的第一个tag=1的节点才对应中序遍历当前pop的节点  
*/

int main()
{
    int N;
    cin>>N;
    struct Node stack[30];
    int flag = 0;
    int size = 0;               //栈元素大小,指向栈顶的下一个位置  
    for ( int i = 0 ; i < 2*N ; i++){
        string str;
        cin>>str;
        if(str[1] == 'u'){
            cin>>stack[size].num;   //入栈  
            stack[size].tag = 1;    //标记第一次入栈  
            size++;
        }else{
            //循环弹出栈顶tag=2的节点 
            while(size > 0 && stack[size-1].tag == 2){
                if( flag){
                    cout<<" ";
                }
                flag = 1;
                cout<<stack[--size].num;
            }
            //将中序遍历中应该要弹出的节点弹出再压栈,做标记即可  
            if ( size>0){
                stack[size-1].tag = 2;
            }

        } 
    }
    while(size){
        if ( flag ){
            cout<<" ";
        }
        flag = 1;
        cout<<stack[--size].num;
    }

    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档