由于您的索引从1开始(索引0包含0-为什么?),因此可以按以下方法确定给定节点子节点的索引:
i
i
的左子节点的索引:2i
i
的右子节点的索引:2i + 1
因此,对于每个节点,您可以轻松检查两个子节点是否都大于该节点本身。
is_heap
是一个很好的建议。你只需要使用适当的比较器即可。而且你甚至可以轻松地将其与迭代器一起使用,以实现基于1的索引:
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
int main()
{
std::vector<int> v {0, 5, 9, 11, 14, 18, 19 };
std::cout << std::is_heap(
v.begin()+1, // off by 1
v.end(),
std::greater<int>() // std::less is used by default for max-heap
);
}
熟悉的广度优先搜索(BFS)也可以应用于检查树是否为最小/最大堆。
#include <iostream>
#include <queue>
int main() {
int tree[] = {5, 9, 11, 14, 18, 19, 21, 33, 17, 27};
int size = 10;
std::queue <int> q;
q.push(0);
bool flag = true;
while(!q.empty()) {
int x = q.front();
q.pop();
int left = 2*x+1, right = 2*x+2; // 0-based indexing used here
if(left < size) { // check if left child exists or not.
q.push(left);
// check value at parent is less than child or not.
if(tree[x] > tree[left]) {
flag = false;
break;
}
}
if(right < size) { // check whether right child exists or not.
q.push(right);
if(tree[x] > tree[right]) { // check value of parent less than child.
flag = false;
break;
}
}
}
if(flag)
std::cout << "It is minimum heap.\n";
else
std::cout << "Not a minimum heap.\n";
return 0;
}
这个想法与wookie919类似。
std::is_heap
函数? - Igor Tandetniki > 1
,都满足a[i] >= a[i/2]
,逐步递减i
更容易。这样,您就不必创建两个潜在的子索引并检查它们是否均在边界内。 - pjs