如何判断一颗完全二叉树
判断完全二叉树

完全二叉树性质
- 除最后一层,全部满节点
- 最后一层结点从左到右依次填满
思路:采用
宽度优先遍历
思路
- 任一结点**有右无左**,返回
false - 在不违反
1.的情况下,遇到第一个单子结点的结点后,剩下的结点必须为**叶节点**
isCBT()方法
inline bool isCBT(Node* head) {
queue<Node*> que;
que.push(head);
bool leaf = false;
while (!que.empty()) {
Node* h = que.front();
Node* l = h->left;
Node* r = h->right;
que.pop();
if (
(l == NULL && r != NULL)
||
(leaf && (l != NULL || r != NULL))
) {
return false;
}
if (l != NULL && r == NULL) {
leaf = true;
}
if (l != NULL) que.push(l);
if (r != NULL) que.push(r);
}
return true;
}
完整 Codes
//判断完全二叉树
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int value;
Node* left;
Node* right;
Node(int v) : value(v), left(NULL), right(NULL) {};
};
inline Node* initTree() {
Node* head = new Node(5);
Node* v3 = new Node(3);
Node* v7 = new Node(7);
Node* v2 = new Node(2);
Node* v4 = new Node(4);
Node* v6 = new Node(6);
Node* v8 = new Node(8);
Node* v1 = new Node(1);
head->left = v3;
head->right = v7;
head->left->left = v2;
head->left->right = v4;
head->left->left->left = v1;
head->right->left = v6;
head->right->right = v8;
return head;
}
inline void traverse(Node* head) {
if (!head) {
return ;
} else {
cout << head->value << ' ';
traverse(head->left);
traverse(head->right);
}
}
inline void widthPriorTraverse(Node* head) {
queue<Node*> que;
que.push(head);
while (!que.empty()) {
Node* h = que.front();
cout << h->value << ' ';
que.pop();
if (h->left) que.push(h->left);
if (h->right) que.push(h->right);
}
}
inline bool isCBT(Node* head) {
queue<Node*> que;
que.push(head);
bool leaf = false;
while (!que.empty()) {
Node* h = que.front();
Node* l = h->left;
Node* r = h->right;
que.pop();
if (
(l == NULL && r != NULL)
||
(leaf && (l != NULL || r != NULL))
) {
return false;
}
if (l != NULL && r == NULL) {
leaf = true;
}
if (l != NULL) que.push(l);
if (r != NULL) que.push(r);
}
return true;
}
int main() {
Node* head = initTree();
widthPriorTraverse(head);
if (isCBT(head)) {
cout << "isCBT" << endl;
} else {
cout << "is_not_CBT" << endl;
}
}


浙公网安备 33010602011771号