PAT A-1130 Infix Expression (25 points)

Title: 1130 Infix Expression (25 points)
Analysis : Output the expression corresponding to the binary tree, just output in the middle order. Note that there are no parentheses on the outermost side.
#include<iostream>
#include<algorithm>
#include<math.h>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
int n,m,k;
struct Node{
    
    
    string key;
    int left,right;
};
int visi[50];
Node node[50];
int beg;
void dfs(int root)
{
    
    
    if(root == -1) return;
    if((node[root].left != -1 || node[root].right != -1 ) && root!=beg)
        cout<<"(";
    dfs(node[root].left);
    cout<<node[root].key;
    dfs(node[root].right);
    if((node[root].left != -1 || node[root].right != -1 ) && root!=beg)
        cout<<")";
}
int main(){
    
    
    cin>>n;
    for(int i = 1; i<= n ;i++)
    {
    
    
        string key;
        int a,b;
        cin>>key>>a>>b;
        node[i].key = key;
        node[i].left = a;
        node[i].right = b;
        visi[a] = visi[b] = 1;
    }
    for(int i = 1; i<= n ;i++)
        if(visi[i] == 0)
        beg = i;
    dfs(beg);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43567222/article/details/114303958
Recommended