6.15 后缀表达式

Link: 4274. 后缀表达式 - AcWing题库

题目要求是对树进行 特殊的 后续遍历

后续遍历: 按照 左 右 子的方法进行遍历

特殊:如果不存在左子树 则先遍历 子 在遍历右边

ADT::
string info; // 存信息
int l;// 左字数的角标
int r;//右子树的脚标

用这种ADT 构建一个 以数组角标为序号的树

后续遍历
// 后续遍历
void dfs(int h){
    if(a[h].l!=-1) dfs(a[h].l);
    if(a[h].r!=-1) dfs(a[h].r);
    cout<<a[h].c<<' ';
    return ;
}

//特殊化:
void dfs(int h){
    if(a[h].l!=-1) dfs(a[h].l);
    if(a[h].l==-1){
        cout<<a[h].c<<' ';
        if(a[h].r!=-1) dfs(a[h].r);
    }else{
        if(a[h].r!=-1) dfs(a[h].r);
        cout<<a[h].c<<' ';
    }
    return ;
}
确定括号

每一个子树都带一个括号 , 一个节点也可以看成子树

寻找根节点

没有被当成子节点的节点 一定是根节点, 所以直接去找所有节点里面 哪个节点没有被当成子节点

#include<iostream>
#include<algorithm>
#include<string>

using namespace std;

typedef struct node{
    int id;
    string c;
    int l,r;
}node;
node a[30];
int t[30]{0};

void dfs(int h){
    cout<<'(';
    if(a[h].l!=-1) dfs(a[h].l);

    if(a[h].l==-1){
        cout<<a[h].c;
        if(a[h].r!=-1) dfs(a[h].r);
        cout<<')';
    }else{
        if(a[h].r!=-1) dfs(a[h].r);
        cout<<a[h].c<<')';
    }
    return ;
}

int main(){
    ios::sync_with_stdio(0);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].c>>a[i].l>>a[i].r;
        if(a[i].l>0) t[a[i].l]=1;
        if(a[i].r>0) t[a[i].r]=1;
    }
    int h;
    for(int i=1;i<=n;i++){
        if(!t[i]){
            h=i;break;
        }
    }
    dfs(h);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值