#include <iostream>
#include <string>
int n=0,dep1=0,dep2=0,m=0,n1=0,n2=0;
template <class T>
struct BiNode
{
T data;
BiNode<T> *lchild, *rchild;
};
template <class T>
class BiTree
{
public:
BiTree() {root=NULL;}
BiTree(T ch);
~BiTree(void);
BiNode<T>* Getroot();
void PreOrder(BiNode<T> *root);
void InOrder(BiNode<T> *root);
void PostOrder(BiNode<T> *root);
void LeverOrder(BiNode<T> *root);
int Count(BiNode<T> *root);
int Depth(BiNode<T> *root);
int leafnum(BiNode<T> *root);
int full(BiNode<T> *root);
private:
BiNode<T> *root;
BiNode<T> *Creat(T ch);
void Release(BiNode<T> *root);
};
template<class T>
BiTree<T>::BiTree(T ch)
{ cout<<"请输入创建一棵二叉树的结点数据"<<endl;
this->root = Creat(ch);
}
template <class T>
BiNode<T>* BiTree<T>::Creat(T ch)
{
BiNode<T>* root;
cin>>ch;
if (ch=="#") root = NULL;
else{
root = new BiNode<T>;
root->data=ch;
root->lchild = Creat(ch);
root->rchild = Creat(ch);
}
return root;
}
template<class T>
BiTree<T>::~BiTree(void)
{
Release(root);
}
template<class T>
BiNode<T>* BiTree<T>::Getroot( )
{
return root;
}
template<class T>
void BiTree<T>::PreOrder(BiNode<T> *root)
{
if(root==NULL) return;
else{
cout<<root->data<<" ";
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
template <class T>
void BiTree<T>::InOrder (BiNode<T> *root)
{
if (root==NULL) return;
else{
InOrder(root->lchild);
cout<<root->data<<" ";
InOrder(root->rchild);
}
}
template <class T>
void BiTree<T>::PostOrder(BiNode<T> *root)
{
if (root==NULL) return;
else{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout<<root->data<<" ";
}
}
template <class T>
void BiTree<T>::LeverOrder(BiNode<T> *root)
{
const int MaxSize = 100;
int front = 0;
int rear = 0;
BiNode<T>* Q[MaxSize];
BiNode<T>* q;
if (root==NULL) return;
else{
Q[rear++] = root;
while (front != rear)
{
q = Q[front++];
cout<<q->data<<" ";
if (q->lchild != NULL) Q[rear++] = q->lchild;
if (q->rchild != NULL) Q[rear++] = q->rchild;
}
}
}
template<class T>
void BiTree<T>::Release(BiNode<T>* root)
{
if (root != NULL){
Release(root->lchild);
Release(root->rchild);
delete root;
}
}
template<class T>
int BiTree<T>::Count(BiNode<T> *root)
{
if(root==NULL) return 0;
else
{
Count(root->lchild);
Count(root->rchild);
n++;
}
return n;
}
template <class T>
int BiTree<T>::Depth(BiNode<T> *root)
{
if (root==NULL) return 0;
else
{
dep1=Depth(root->lchild);
dep2=Depth(root->rchild);
if(dep1>dep2) return dep1+1;
else return dep2+1;
}
}
template <class T>
int BiTree<T>::leafnum(BiNode<T> *root)
{
if(root==NULL) return 0;
else
{
if(root->lchild==NULL && root->rchild==NULL)
m++;
leafnum(root->lchild);
leafnum(root->rchild);
}
return m;
}
template <class T>
int BiTree<T>::full(BiNode<T> *root)
{
if(root==NULL) return 0;
else
{
if(root->lchild==NULL && root->rchild==NULL)
return 1;
else if (root->lchild==NULL || root->rchild==NULL)
return 0;
else return(full(root->lchild) && full(root->rchild));
}
}