判断完全二叉树

完全二叉树性质
- 除最后一层,全部满节点
- 最后一层结点从左到右依次填满
思路:采用宽度优先遍历

思路
- 任一结点**有右无左**,返回
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; |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码