DFS树的遍历
1.完全二叉树的遍历,$数组index从1开始,左Child = parent * 2, 右Child = parent * 2 + 1$
2.到达叶结点,打印搜索路径
C++ 代码
#include <iostream>
using namespace std;
const int MAX_N = 1010;
int heap[MAX_N];
int path[MAX_N];
int n;
bool isMinHeap, isMaxHeap;
void DFS(int v, int step) {
path[step] = heap[v];
if (v * 2 > n) {
for (int i = 0; i <= step; i++) {
if (i) {
if (path[i] > path[i - 1]) isMinHeap = true;
else if (path[i] < path[i - 1]) isMaxHeap = true;
printf(" ");
}
printf("%d", path[i]);
}
cout << endl;
return;
}
if (v * 2 + 1 <= n) {
DFS(v * 2 + 1, step + 1);
}
if (v * 2 <= n) {
DFS(v * 2, step + 1);
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> heap[i];
}
DFS(1, 0);
if (isMaxHeap && isMinHeap) puts("Not Heap");
else if (isMaxHeap) puts("Max Heap");
else puts("Min Heap");
return 0;
}
🐂