本文共 2625 字,大约阅读时间需要 8 分钟。
树的结构设计是解决这道题的关键。根据题意,我们需要用4个数组来表示一棵树,其中:
通过这种设计,我们可以用两个方向的指针来表示树的左、右孩子,从而实现对树的遍历。
#include#include #include using namespace std;int a[100010][4];void DFS(int x) { if (x == 0) return; cout << x << " "; if (a[x][2]) DFS(a[x][2]); if (a[x][3]) DFS(a[x][3]); return;}int main() { ios::sync_with_stdio(false); int i, n, len = 0, tem; memset(a, 0, sizeof(a)); for (cin >> n, i = 1; i <= n; ++i) { cin >> tem; a[tem][0] = i; } for (i = 1; i <= n; ++i) { for (tem = len; tem && a[a[tem][1]][0] > a[i][0]; --tem) { if (tem) a[a[tem][1]][3] = i; } if (tem) a[a[tem][1]][3] = i; if (tem) a[a[tem][1]][3] = i; }}
树的结构设计是解决这道题的关键。根据题意,我们需要用4个数组来表示一棵树,其中:
通过这种设计,我们可以用两个方向的指针来表示树的左、右孩子,从而实现对树的遍历。
#include#include #include using namespace std;int a[100010][4];void DFS(int x) { if (x == 0) return; if (a[x][2]) { cout << a[x][2]; if (a[a[x][2]][2]) { cout << " "; if (a[a[x][2]][2]) { cout << a[a[x][2]][2]; } } } if (a[x][3]) { cout << " "; if (a[a[x][3]][2]) { cout << a[a[x][3]][2]; } } return;}int main() { ios::sync_with_stdio(false); int i, n, len = 0, tem; memset(a, 0, sizeof(a)); for (cin >> n, i = 1; i <= n; ++i) { cin >> tem; a[tem][0] = i; } for (i = 1; i <= n; ++i) { for (tem = len; tem && a[a[tem][1]][0] > a[i][0]; --tem) { if (tem) a[a[tem][1]][3] = i; } if (tem) a[a[tem][1]][3] = i; if (tem) a[a[tem][1]][3] = i; }}
树的结构设计是解决这道题的关键。根据题意,我们需要用4个数组来表示一棵树,其中:
通过这种设计,我们可以用两个方向的指针来表示树的左、右孩子,从而实现对树的遍历。
#include#include #include using namespace std;int a[100010][4];void DFS(int x) { if (x == 0) return; cout << x << " "; if (a[x][2]) { DFS(a[x][2]); } if (a[x][3]) { DFS(a[x][3]); } return;}int main() { ios::sync_with_stdio(false); int i, n, len = 0, tem; memset(a, 0, sizeof(a)); for (cin >> n, i = 1; i <= n; ++i) { cin >> tem; a[tem][0] = i; } for (i = 1; i <= n; ++i) { for (tem = len; tem && a[a[tem][1]][0] > a[i][0]; --tem) { if (tem) a[a[tem][1]][3] = i; } if (tem) a[a[tem][1]][3] = i; if (tem) a[a[tem][1]][3] = i; }}
转载地址:http://wrze.baihongyu.com/