PAT(甲级)1086 Tree Traversals Again (25point(s))

题目

题目链接

思路

用栈模拟树的遍历;
这道题的核心是要明白入队顺序就是先序遍历的顺序;出队顺序为中序遍历的顺序;
理解了这一点,题目就转化为已知先序和中序,输出后序;

单词

implemented:实施,应用;
recursive [rɪˈkɜːsɪv] :递归的,循环的 ;

代码
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <math.h>
using namespace std;
const int maxn = 35;
int cnt = 0, n;//后序输出节点的个数
struct node{
     int data;
     node *left, *right;
};
int pre[maxn], in[maxn];//存储先序和中序
//建树
node* create(int preL, int preR, int inL, int inR){
     if(preL > preR) return NULL;
     node* root = new node;//返回的根节点
     root -> data = pre[preL];
     int k = inL;
     //在中序中找到根节点,将子树一分为二
     while(k <= inR && in[k] != pre[preL]) k ++;
     int num = k - inL;
     //分别递归构建左子树和右子树
     root -> left = create(preL + 1, preL + num, inL, k - 1);
     root -> right = create(preL + num + 1, preR, k + 1, inR);
     return root;
}
void postOrder(node* root){
     if(root == NULL) return;
     postOrder(root -> left);
     postOrder(root -> right);
     printf("%d", root->data);
     cnt ++;
     if(cnt != n) printf(" ");
     return;
}
int main()
{
     int preIdx = 0, inIdx = 0;
     stack<int> st;//栈
     scanf("%d", &n);
     string ss;
     for(int i = 0; i < 2 * n; i ++){
          cin >> ss;
          if(ss == "Push"){
               scanf("%d", &pre[preIdx++]);
               st.push(pre[preIdx - 1]);
          }
          else{
               in[inIdx ++] = st.top();
               st.pop();
          }
     }
     node* root = create(0, n - 1, 0, n -1);
     postOrder(root);
     system("pause");
     return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值