如何判断一颗完全二叉树

判断完全二叉树

完全二叉树

完全二叉树性质

  • 除最后一层,全部满节点
  • 最后一层结点从左到右依次填满

思路:采用宽度优先遍历 宽度优先遍历

思路

  1. 任一结点**有右无左**,返回 false
  2. 在不违反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;
}
}
posted @   IoOozZzz  阅读(13)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示