0
点赞
收藏
分享

微信扫一扫

1130 Infix Expression (25 分) (中序遍历 二叉树

东林梁 2022-02-22 阅读 94

添加链接描述
中序遍历 且带括号

#include<bits/stdc++.h>
using namespace std;
const int N=30;
struct node{
    string data;
    int l,r;
    // bool operator<(const node &ch)const {}
}t[N];
int vis[N];
int root=1;
void dfs(int u){
    if(u==-1)return;
    if(t[u].r!=-1&&u!=root)cout<<"(";//如果这个结点有右子树 说明他不是叶子结点   并且如果他不是根  那就有括号
    dfs(t[u].l);//如果他没有右子树 那也就没有左子树了  因为够不成算式      那就不需要
    cout<<t[u].data;
    dfs(t[u].r);
    if(t[u].r!=-1&&u!=root)cout<<")";
}
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        string ch;
        int a,b;
        cin>>ch>>a>>b;
        t[i]={ch,a,b};
        if(a!=-1)vis[a]++;
        if(b!=-1)vis[b]++;
    }
    
    while(vis[root])root++;
    // cout<<root<<endl;
    dfs(root);
    return 0;
}
举报

相关推荐

0 条评论