6 solutions
-
6
#include<iostream> #include<string> using namespace std; string xian,zhong; // 先序遍历和中序遍历,一棵子树的遍历序列是连续的。在递归处理过程中,需要 l1、r1 两个变量 // 去卡当前子树的先序序列,l2、r2 去卡当前子树的中序序列。 void f(int l1, int r1, int l2, int r2) { int m=zhong.find(xian[l1]); // 结合样例,动手画草稿,算清楚数量关系。 // 这也是在做其他比较复杂的题目时应该要采取的做法。 if(m>l2) f(l1+1,l1+m-l2, l2,m-1); if(m<r2) f(l1+m-l2+1,r1, m+1,r2); cout<<xian[l1]; } int main() { cin>>xian>>zhong; f(0, xian.size()-1, 0, zhong.size()-1); return 0; }
-
1
#include <bits/stdc++.h> using namespace std; //最后输出根节点。 // 根据先序和中序遍历构建二叉树并输出后序遍历 void bianli(string& x, string& z) { if (x.empty() || z.empty())//遍历完成 { return; } // 先序遍历的第一个字符是根节点 char root = x[0]; // 在中序遍历中找到根节点的位置 int rootz = z.find(root); //C++ 中的 substr() 函数用于复制子字符串, //从指定位置开始,直到指定长度。 //如果没有指定长度或指定长度超出源字符串的长度, //则子字符串将延续到源字符串的结尾 // 分割中序遍历序列为左子树和右子树 string lz = z.substr(0, rootz); string rz = z.substr(rootz + 1); // 分割先序遍历序列为左子树和右子树 string lx = x.substr(1, lz.length()); string rx = x.substr(1 + lz.length()); // 递归构建左子树并输出后序遍历 bianli(lx, lz); // 递归构建右子树并输出后序遍历 bianli(rx, rz); // 输出根节点 cout << root; } int main() { string x, z; // 输入先序遍历序列 cin >> x; // 输入中序遍历序列 cin >> z; // 构建并输出后序遍历序列 bianli(x, z); return 0; }
-
1
#include<bits/stdc++.h> using namespace std; struct node{ char v; int l,r; }; node g[100010]; node hou[10010]; int w=0; int dfs(string x,string z){ if(x.size()==0)return -1;//字符串为空时返回 int k=z.find(x[0]);//k来划分左右子树 w++;// int s=w;//s表示当前字母位置 hou[s].v=x[0];//先序遍历的第一个一定为根节点,后序遍历的最后一个 string h1=z.substr(0,k);//左子树部分 string h2=x.substr(1,k);//左子树部分 string h3=x.substr(k+1,x.size()-k);//右子树部分 string h4=z.substr(k+1,z.size()-k);//右子树部分 //后序遍历为左右根 hou[k].l=dfs(h2,h1); hou[k].r=dfs(h3,h4); cout<<hou[s].v; return s; } int main(){ string xian,zhong; cin>>xian>>zhong; dfs(xian,zhong); return 0; }
-
-4
#include<bits/stdc++.h> #define long long long using namespace std; string fro,mid; main(){ cin>>fro>>mid; void beh(int,int,int,int); beh(0,fro.size(),0,mid.size()); } //递归 void beh(int fro_lef,int fro_rig,int mid_lef,int mid_rig){ if(mid_rig-mid_lef==1){ cout<<mid[mid_lef]; return; } int i=mid_lef; while(fro[fro_lef]!=mid[i]) i++; if(i!=mid_lef) beh(fro_lef+1,fro_lef+i-mid_lef+1,mid_lef,i); if(mid_rig!=i+1) beh(fro_lef+i-mid_lef+1,fro_rig,i+1,mid_rig); cout<<fro[fro_lef]; }
- 1
Information
- ID
- 824
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 4
- Tags
- # Submissions
- 74
- Accepted
- 34
- Uploaded By