C++判断完全二叉树

#include<iostream>
#include<stdlib.h> 
#include<deque>  //插入标准库中的头文件
using namespace std;

typedef struct treenode
{
	char data;
	treenode *right;
	treenode *left;
}*Node;

//创建二叉树
void creat_tree(treenode *&rt)
{
	char ch;
	ch = getchar();
	if ('#' == ch) {
		rt = NULL;
	} else {
		rt = new treenode;
		rt->data = ch;
		creat_tree(rt->left);        //构造左子树
		creat_tree(rt->right);    //构造右子树    
	}
}

//层次遍历
bool Complete_binary_tree(treenode *&root) { //在这里采用层次遍历的方法
	if (root == NULL) { //空树满足条件
		return 1;
	}

	deque <Node> c;  //定义一个空的队列
	c.push_back(root);
	while (!c.empty()) {  //如果队列不为空
		Node temp = c.front();  //返回队列的第一个元素
		if (temp) {  //如果是非空结点
			cout << temp->data << " ";
			c.pop_front();  //出队列

			c.push_back(temp->left);  //左孩子
			c.push_back(temp->right); //右孩子
		}
		else {
			while (!c.empty()) {
				Node temp = c.front();
				c.pop_front();  //出队列
				if (temp) {  //结点非空
					return 0;
				}
			}
		}
	}
	return 1;
}
int main() {
	treenode *root = NULL;
	cout << "请输入二叉树,空值以#代表:" << endl;
	creat_tree(root);        //创建二叉树
	cout << Complete_binary_tree(root) << endl;

	system("pause");
	return 0;
}

/*
如果想实现反序输出,只需要在这里添加一个栈就可以实现了。
*/

/*
ABD##E##CF###
ABD##E##C#F##
*/


猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/80357610