1.问题1 给一个树的中序遍历,与后序遍历,要你输出前序遍历.下面直接给出核心代码.
void dfs(int L1,int R1,int L2,int R2){
if(L1>R1) return ;
char root=post[R2]; int p=0;coutx) a[n++]=x;
return n>0;
}
妙啊. 不知道读入个数,但知道输入数据只有一行,直接用getline函数. 用法是getline(cin,变量) 如果读不到数据,就返回NULL(也就是0) stringstream 好啊,自动识别类型 这函数还顺带统计了·有多少个数字(n-1)
Ac code:
#include
#include
#include
#include
using namespace std;
const int maxv=10000+10;
int in_order[maxv],post_order[maxv],lch[maxv],rch[maxv],n;int ans,minsum;
bool rread(int *a){ string line;
while(!getline(cin,line)) return false;
int x;n=0;
stringstream ss(line);
while(ss>>x) a[n++]=x;
return n>0;
}
int rec(int L1,int R1,int L2,int R2){
if(L1>R1) return 0;
int root=post_order[R2];int p=0;
while(in_order[p]!=root) p++;
int cnt=p-L1;
lch[root]=rec(L1,p-1,L2,L2+cnt-1);
rch[root]=rec(p+1,R1,L2+cnt,R2-1);
return root;
}
void dfs(int u,int sum){
sum+=u;
if(!lch[u]&&(!rch[u])){
if((sum
关注
打赏