PAT 1130. Infix Expression (25) 前缀表达式、树的中序遍历
2017-09-15 15:46
417 查看
#include<cmath> #include<algorithm> #include<cstring> #include<iostream> #include<stack> #include<vector> #include<queue> #include<string> #include<map> using namespace std; //30min //耗时于思考和编写程序 /************************* 题意:给出一个前缀表达式树结构,求该表达式并加上括号 叶结点为运算数 非叶节点为运算符 *************************/ /************************ 求解要点:根据样例可知为中序遍历 难点为加括号 注意当子树 为 非叶节点 时才加括号,并要成对加 即 { 加括号 递归 加括号 输出 加括号 递归 加括号 } 注意点:根节点判断、叶节点判断、递归边界 ************************/ /*********************** 笔记: left、right为系统变量 *********************/ #define INF 0xfffffff //int32位,去除首位符号位,最大为该值 #define M 60000 int n,m; string node[M]; int father[M],Right[M],Left[M]; int leaf[M]; void preb(int noden) { if(noden==-1) return ; //左子树非空且叶节点,可加括号 if(Left[noden]!=-1 && leaf[Left[noden]]!=1) cout<<"("; preb(Left[noden]); if(Left[noden]!=-1 && leaf[Left[noden]]!=1) cout<<")"; cout<<node[noden]; if(Right[noden]!=-1 && leaf[Right[noden]]!=1) cout<<"("; preb(Right[noden]); if(Right[noden]!=-1 && leaf[Right[noden]]!=1) cout<<")"; } int main() { int n,i,j,l,r,root; scanf("%d",&n); memset(father,0,sizeof(father)); memset(leaf,0,sizeof(leaf)); for(i=1;i<=n;i++) { cin>>node[i]; scanf("%d%d",&l,&r); Left[i]=l; father[l]=1; Right[i]=r; father[r]=1; if(l==-1&&r==-1) leaf[i]=1; } for(i=1;i<=n;i++) if(father[i]==0) { root=i; break; } preb(root); cout<<endl; return 0; }
相关文章推荐
- PAT 02-3. 求前缀表达式的值(25)
- PAT 1130. Infix Expression (25) 折腾表达式,未解之谜
- PAT1023. 求前缀表达式的值(25)
- 3-07. 求前缀表达式的值(25) (ZJU_PAT数学)
- 3-07. 求前缀表达式的值(25) (ZJU_PAT数学)
- PAT甲题题解-1130. Infix Expression (25)-中序遍历
- PAT 02-3. 求前缀表达式的值(25) Python
- PAT - 甲级 - 1130. Infix Expression (25) (中序遍历)
- PAT 数据结构 02-线性结构3. 求前缀表达式的值(25)
- PAT (Advanced Level) Practise 1130 Infix Expression (25)
- [数据结构]7-21 求前缀表达式的值(25 分)
- pat Data_Structure 前缀表达式的计算--堆栈法
- 3-06. 表达式转换(25)(中缀表达式转后缀表达式ZJU_PAT)
- 3-07. 求前缀表达式的值(25)
- PAT 求前缀表达式的值
- PAT 1086. Tree Traversals Again (25)(依据中序遍历的非递归形式用到的堆的状态,来构造树并输出后序遍历)
- PAT3-07. 求前缀表达式的值
- 02-线性结构3. 求前缀表达式的值(25)
- 浙大PAT 3-07. 求前缀表达式的值 (解题思路)
- PAT-A1130. 二叉树-中序遍历 变形输出