//Tree.h
#include <iostream>
#define MaxSize 1000
using namespace std;
template <class T> class BiTree;
template <class T>
class BiNode{
friend BiTree<T>;
T data;
BiNode* lchild;
BiNode* rchild;
};
template <class T>
class BiTree
{
BiNode<T> *root;
public:
BiTree() ;
~BiTree();
void Release(BiNode<T> *root);
void LevelOrder(BiNode<T> *root);
BiNode<T>* Creat();
int countNodes( BiNode<T> *root );
int Height( BiNode<T> *root);
};
template <class T>
void BiTree<T>::LevelOrder(BiNode<T> *root)
{
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>
BiNode<T>* BiTree<T>::Creat()
{
BiNode<T> *root=NULL;
T ch;
cout<<"Input Node:";
if((ch=getchar())!='#')
{
getchar();//jieshouhuiche
root = new BiNode<T>;
root->data = ch;
root->lchild=Creat();
root->rchild=Creat( );
}
else
getchar();
return root;
}
template <class T>
BiTree<T>::~BiTree( )
{
Release(BiNode<T> *root);
}
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>::countNodes( BiNode<T> *root )
{
if ( root == NULL )
return 0;
else{
int count = 1;
count += countNodes(root->lchild);
count += countNodes(root->rchild);
return count;
}
}
template<class T>
int BiTree<T>::Height( BiNode<T> *root )
{
int u,n;
if(root==NULL) return 0;
u=Height(root->lchild);
n=Height(root->rchild);
if(u>n) return(u+1);
return(n+1);
}
//tree.cpp
#include<iostream>
#include"Tree.h"
using namespace std;
int main()
{
BiTree<char> *bt=NULL;
BiNode<char> *rootNode=NULL;
rootNode=bt->Creat();
cout << "count=" << bt->countNodes( rootNode ) << endl;
cout << "height=" << bt->Height( rootNode ) << endl;
cout << "LevelOrder:/n";
bt->LevelOrder(rootNode);
getchar();
system("cls");
return 0;
}
/*运行结果:
*/