zoukankan      html  css  js  c++  java
  • 中国大学MOOC数据结构基础习题集、033、Tree Traversals Again

    题目链接:http://www.patest.cn/contests/mooc-ds/03-3

    题目分析:借助“栈”进行树的后续遍历。栈工作记录中必须注明刚才是在左子树还是在右子树中。

      每次PUSH,times = 1;

      每次POP检查栈顶记录的times:如果是1,弹出来变成2压回栈;

                      如果是2,则弹出,放入存放结果的vector中,重复这一过程,直到栈顶times为1。

      所有PUSH与POP操作执行完毕时,输出vector内的数据和stack中的数据即可。注意要处理最后的空格。

    代码分析:

      头文件声明:1~4  

      定义数据结构:5~14

      按照题目分析所说:15~57

      输出结果:58~70

     1 #include <iostream>
     2 #include <stack>
     3 #include <vector>
     4 using namespace std;
     5 typedef struct node
     6 {
     7     int data;
     8     int times;
     9     node(int d, int t)
    10         :data(d), times(t)
    11     {
    12 
    13     };
    14 } Node;
    15 int main()
    16 {
    17     int n;
    18     cin >> n;
    19     string cmd;
    20     int x;
    21     stack<Node> sta;
    22     vector<int> vec;
    23     for(int i=0; i<2*n; i++)
    24     {
    25         cin >> cmd;
    26         if(cmd == "Push")
    27         {
    28             cin >> x;
    29             sta.push(Node(x, 1));
    30         }
    31         if(cmd == "Pop")
    32         {
    33             Node node = sta.top();
    34             sta.pop();
    35             if(node.times == 1)
    36             {
    37                 node.times = 2;
    38                 sta.push(node);
    39             }
    40             else if(node.times == 2)
    41             {
    42                 vec.push_back(node.data);
    43                 while(sta.top().times == 2)
    44                 {
    45                     vec.push_back(sta.top().data);
    46                     sta.pop();
    47                 }
    48                 if (sta.size() != 0)
    49                 {
    50                     node = sta.top();
    51                     node.times = 2;
    52                     sta.pop();
    53                     sta.push(node);
    54                 }
    55             }
    56         }
    57     }
    58     for(int i=0; i<vec.size(); i++)
    59     {
    60         cout << vec[i]<< " ";
    61     }
    62     while(sta.size() != 0)
    63     {
    64         cout << sta.top().data;
    65         sta.pop();
    66         if(sta.size() != 0)
    67             cout << " ";
    68     }
    69     return 0;
    70 }

    AC成果:

  • 相关阅读:
    linux下shell显示-bash-4.1#不显示路径解决方法
    update chnroute
    An error "Host key verification failed" when you connect to other computer by OSX SSH
    使用dig查询dns解析
    DNS被污染后
    TunnelBroker for EdgeRouter 后记
    mdadm详细使用手册
    关于尼康黄的原因
    Panda3d code in github
    Python实例浅谈之三Python与C/C++相互调用
  • 原文地址:https://www.cnblogs.com/clevercong/p/4177802.html
Copyright © 2011-2022 走看看