• 中国大学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成果:

  • 相关阅读:
    Spring Batch与ETL工具比较
    Spring Batch基本概念
    SpringBatch介绍
    2019第51周日
    用arthas的watch方法观察执行方法的输入输出
    三人行必有我师
    用arthas查看JVM已加载的类及方法信息
    线上问题排查利器Arthas
    换个视觉
    Java Servlet:服务器小程序
  • 原文地址:https://www.cnblogs.com/clevercong/p/4177802.html
Copyright © 2020-2023  润新知