//2018//11//29//18:30--19:05
//还不错,数组别越界啊记得
//另外这是个偷懒的做法,因为数组长度是随便选的,没有去求树的高度
//另外我把高度补上了
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
template<class T>
class BinaryTreeNode{
public:
T data;
BinaryTreeNode<T> *leftchild;
BinaryTreeNode<T> *rightchild;
BinaryTreeNode(T data = 0){
this->data = data;
this->leftchild = NULL;
this->rightchild = NULL;
}
};
template<class T>
class BinaryTree{
private:
BinaryTreeNode<T> *root;
public:
BinaryTree(){
this->root = NULL;
}
BinaryTreeNode<T>* Create(BinaryTreeNode<T> *root); //创建链表
void preOrder(BinaryTreeNode<T> *root); //先序遍历
bool Iscomplete(BinaryTreeNode<T> *root); //判断是否为完全二叉树
void width(BinaryTreeNode<T> *root,int *shuzu,int& max,int ceng); //计算二叉树的宽度
int height(BinaryTreeNode<T> *root); //计算二叉树的高度
};
template<class T>
BinaryTreeNode<T>* BinaryTree<T>:: Create(BinaryTreeNode<T> *root){
char x;
cin >> x;
if(x == '#')
return NULL;
else{
root = new BinaryTreeNode<T>(x);
root ->leftchild = Create(root->leftchild);
root->rightchild = Create(root->rightchild);
return root;
}
}
template<class T>
void BinaryTree<T> :: preOrder(BinaryTreeNode<T> *root){
if(root != NULL){
cout << root -> data<< " " ;
preOrder(root->leftchild);
preOrder(root->rightchild);
}
}
template<class T>
bool BinaryTree<T> :: Iscomplete(BinaryTreeNode<T> *root){
using std :: queue;
queue<BinaryTreeNode<T>* > que;
BinaryTreeNode<T> *p;
while(root != NULL){
que.push(root->leftchild);
que.push(root->rightchild);
root = que.front();
que.pop();
}
while(!que.empty()){
p = que.front();
que.pop();
if(p != NULL)
return false;
}
return true;
}
template<class T>
void BinaryTree<T> :: width(BinaryTreeNode<T> *root,int *shuzu,int& max,int ceng){
if(root != NULL){
shuzu[ceng] += 1;
width(root->leftchild,shuzu,max,ceng +1);
width(root->rightchild,shuzu,max,ceng + 1);
if(max < shuzu[ceng])
max = shuzu[ceng];
}
}
template<class T>
int BinaryTree<T> :: height(BinaryTreeNode<T> *root){
if(root == NULL)
return 0;
else
return max(1+height(root ->leftchild),1+height(root->rightchild));
}
int main(){
BinaryTreeNode<char> *root;
BinaryTree<char> *t;
int ceng = 0;
int maxnum = 0;
cout << "请输入:" << endl;
root = t->Create(root);
int hei = t->height(root);
int *shuzu = new int[hei];
for(int i = 0; i <6;i++)
shuzu[i] = 0;
cout << "构建的二叉树的先序序列为:" << endl;
t->preOrder(root);
if(t->Iscomplete(root))
cout << endl<< "该二叉树是完全二叉树" << endl;
else
cout << endl <<"该二叉树不是完全二叉树" << endl;
cout << "该二叉树的宽度为:";
t->width(root,shuzu,maxnum,ceng);
cout << maxnum;
return 0;
}