中国大学MOOC-数据结构基础习题集、03-3、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成果:

转载于:https://www.cnblogs.com/clevercong/p/4177802.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值