PAT (Advanced Level) Practice 1086 Tree Traversals Again

根据操作写递归就行了,注意一点,data不是从1到n顺序来的,所以要自己去获取push后面的数字,不能简单的用计数器++。 

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;
struct node{
    node* lchild;
    node* rchild;
    int data;
};
vector<int> v;
string op[100];
int index=0,n;
node* createTree(){
    if(index>=2*n) return NULL;

    if(op[index][1]=='u'){//push
        node* root = new node;
        string s = op[index];
        s.erase(0,5);
        int sum=0;
        for(int i=0;i<s.size();i++){
            sum=sum*10 + s[i]-'0';
        }
        root->data=sum;
        index++;
        root->lchild=createTree();
        root->rchild=createTree();
        return root;
    }else{
        index++;
        return NULL;
    }
}
void posttravel(node* root){
    if(root!=NULL){
        posttravel(root->lchild);
        posttravel(root->rchild);
        v.push_back(root->data);
    }
}
int main()
{
    cin>>n;
    getchar();
    for(int i=0;i<2*n;i++){
        getline(cin,op[i]);
    }
    node* root = createTree();
    posttravel(root);
    for(int i=0;i<v.size();i++){
        cout<<v[i];
        if(i!=v.size()-1) cout<<" ";
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值