题目:
错误代码:
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
string p[35];
void LXR(string zx, string hx,int c) {
if (zx.size() > 0) {
char ch = hx[hx.size() - 1];
p[c] = p[c] + ch;
int f = zx.find(ch);
LXR(zx.substr(0, f), hx.substr(0, f), c + 1);
LXR(zx.substr(f + 1), hx.substr(f, zx.size() - f - 1), c + 1);
}
}
void QJ() {
int c = 0;
while (p[c].size() > 0) {
//cout << c << ":";
for (int i = 0; i < p[c].size(); i++) {
if (i == 0 && c == 0) {
cout << p[c][i];
}
else {
cout << " " << p[c][i];
}
}
//cout << endl;
c++;
}
}
int main() {
int N;
string t;
cin >> N;
string a, b;
for (int i = 0; i < N; i++) {
cin >> t;
//a = a + to_string(t);
for (int j = 0; j < t.size(); j++) {
a = a + t[j];
}
}
for (int i = 0; i < N; i++) {
cin >> t;
//b = b + to_string(t);
for (int j = 0; j < t.size(); j++) {
b = b + t[j];
}
}
//cout << "zx:" << b << "\n" << "hx:" << a << endl;
LXR(b, a, 0);
QJ();
return 0;
}
错误原因:样例虽然能过,但是也是碰巧而已,因为样例刚好都是个位数,没有十位数甚至更高位数的数字出现,一旦出现我们这个代码就会输出错误结果。我们应该保证我们的每一个数字都是一个个体,而不是一位数字是一个个体。因此,我们不能够盲目的使用string来简化我们的代码。于是,便产生了下面的这个代码。
AC代码:
#include<iostream>
#include<vector>
using namespace std;
vector<int> p[35];
int SB(int* a) {
//int x = -1;
for (int i = 34; i >= 0; i--) {
if (a[i] != 0) {
return a[i];
}
}
return -1;
}
int LOVE(int* x, int c) {
for (int i = 0; i < 35; i++) {
if (x[i] == c) {
return i;
}
}
return -1;
}
void QJ(int* a, int* b, int c) {
if (a[0] != 0) {
int ch = SB(b);
p[c].push_back(ch);
int x = LOVE(a, ch);
int m[35] = { 0 }, n[35] = { 0 };
int e[35] = { 0 }, f[35] = { 0 };
for (int i = 0; i < x; i++) {
m[i] = a[i];
n[i] = b[i];
}
int cnt = 0;
for (int i = x + 1; i < 35 && b[i] != 0; i++) {
e[cnt] = a[i];
cnt++;
}
cnt = 0;
for (int i = x; i < 35 && b[i] != ch; i++) {
f[cnt] = b[i];
cnt++;
}
QJ(m, n, c + 1);
QJ(e, f, c + 1);
}
}
void LXR() {
int c = 0;
while (p[c].size() != 0) {
vector<int>::iterator pos;
for (pos = p[c].begin(); pos != p[c].end(); pos++) {
if (pos == p[c].begin() && c == 0) {
cout << *pos;
}
else {
cout << " " << *pos;
}
}
c++;
}
}
int main() {
int N;
int zx[35] = { 0 }, hx[35] = { 0 };
cin >> N;
for (int i = 0; i < N; i++) {
cin >> hx[i];
}
for (int i = 0; i < N; i++) {
cin >> zx[i];
}
//cout << sizeof(hx) / sizeof(hx[0]) << " " << sizeof(zx) / sizeof(zx[0]) << endl;
QJ(zx, hx, 0);
LXR();
return 0;
}
思路:直接就用数组来存储我们的数字,利用上述的string的做法,将我们的数组进行切分操作。
易错点:我们在切分后序遍历数组的第二部分,即一个根的右孩子的时候,我们不能够像中序遍历的那样,直接从根的下一个开始到尾巴结束。后续遍历的右孩子可以看成是从中序遍历的根的下标位置到结束的前一个截止。(后序遍历最后一个是根节点)。