码迷,mamicode.com
首页 > 其他好文 > 详细

PAT甲题题解-1130. Infix Expression (25)-中序遍历

时间:2017-04-30 18:37:54      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:scanf   node   复制   splay   exp   target   style   express   lan   

博主欢迎转载,但请给出本文链接,我尊重你,你尊重我,谢谢~
http://www.cnblogs.com/chenxiwenruo/p/6789828.html
特别不喜欢那些随便转载别人的原创文章又不给出链接的
所以不准偷偷复制博主的博客噢~~

 

水,中序遍历输出即可
注意除根节点、叶子节点外,都需要有括号括起来

技术分享
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=25;
int n;
struct Node{
    char str[15];
    int left;
    int right;
}node[maxn];


void dfs(int u,int root){
    if(node[u].left==-1 && node[u].right==-1){
        printf("%s",node[u].str);
        return;
    }
    if(u!=root)
        printf("(");
    if(node[u].left!=-1)
        dfs(node[u].left,root);
    printf("%s",node[u].str);
    if(node[u].right!=-1)
        dfs(node[u].right,root);
    if(u!=root)
        printf(")");
}
int main()
{
    char s[15];
    int l,r;
    int vis[maxn];
    memset(vis,0,sizeof(vis));
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%s %d %d",node[i].str,&l,&r);
        node[i].left=l;
        node[i].right=r;
        vis[l]=vis[r]=1;
    }
    int root;
    for(int i=1;i<=n;i++){
        if(!vis[i]){
            root=i;
            break;
        }
    }
    dfs(root,root);
    return 0;
}
View Code

 

PAT甲题题解-1130. Infix Expression (25)-中序遍历

标签:scanf   node   复制   splay   exp   target   style   express   lan   

原文地址:http://www.cnblogs.com/chenxiwenruo/p/6789828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!