如何判断一颗完全二叉树

本文介绍了如何使用C++编程语言实现完全二叉树的判断,通过宽度优先遍历策略以及isCBT函数,检查一个给定的二叉树是否满足完全二叉树的性质。

判断完全二叉树

完全二叉树

完全二叉树性质

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

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

思路

  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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值