一 代码:
#include <iostream>
#include<stdio.h>
#include<windows.h>
#include <string.h>
using namespace std;
template<class ElemType>
struct Node
{
ElemType data;
Node<ElemType> *leftChild;
Node<ElemType> *rightChild;
Node()
{
leftChild=rightChild=NULL;
}
Node(ElemType &val,Node<ElemType> *left=NULL,Node<ElemType> *right=NULL)
{
data=val;
leftChild=left;
rightChild=right;
}
};
template<class ElemType>
class BinaryTree
{
protected:
Node<ElemType> *root;
int count,t=0;
void PreOrderHelp(Node<ElemType> *r)
{
if(r!=NULL)
{
cout<<r->data<<" ";
PreOrderHelp(r->leftChild);
PreOrderHelp(r->rightChild);
}
}
void InOrderHelp(Node<ElemType> *r)
{
if(r!=NULL)
{
InOrderHelp(r->leftChild);
cout<<r->data<<" ";
InOrderHelp(r->rightChild);
}
}
void PostOrderHelp(Node<ElemType> *r)
{
if(r!=NULL)
{
PostOrderHelp(r->leftChild);
PostOrderHelp(r->rightChild);
cout<<r->data<<" ";
}
}
int HightHelp(Node<ElemType> *r)
{
if(r==NULL) return 0;
else
{
int a,b;
a=HightHelp(r->leftChild);
b=HightHelp(r->rightChild);
//cout<<((a>b?a:b)+1)<<" f";
return ((a>b?a:b)+1);
}
}
int NodeCountHelp(Node<ElemType> *r)
{
if(r==NULL) return 0;
else
{
return NodeCountHelp(r->leftChild)+NodeCountHelp(r->rightChild)+1;
}
}
void DestroyHelp(Node<ElemType> *&r)
{
if(r!=NULL)
{
DestroyHelp(r->leftChild);
DestroyHelp(r->rightChild);
delete r;
r=NULL;
}
}
int LipHelp(Node<ElemType> *r)
{
if(t==0){count=0;t++;}
if(r==NULL) count+=0;
if(r->leftChild==NULL&&r->rightChild==NULL) count+=1;
else
{
LipHelp(r->leftChild);
LipHelp(r->rightChild);
}
return count;
}
Node<ElemType>* CreatTree()
{
char ch=getchar();
Node<ElemType>* pnode;
if (ch == '#')
pnode = NULL;
else
{
pnode = new Node<ElemType>;
pnode->data = ch;
pnode->leftChild = CreatTree();
pnode->rightChild = CreatTree();
}
return pnode;
}
public:
BinaryTree()
{
root=new Node<ElemType>;
root=CreatTree();
}
~BinaryTree()
{
DestroyHelp(root);
}
Node<ElemType>* GetRoot()
{
return root;
}
bool Empty()
{
return root==NULL;
}
void PreOrder()
{
PreOrderHelp(root);
}
void InOrder()
{
InOrderHelp(root);
}
void PostOrder()
{
PostOrderHelp(root);
}
int NodeCount()
{
return NodeCountHelp(root);
}
int Hight()
{
return HightHelp(root);
}
int Lip()
{
return NodeCountHelp(root)-LipHelp(root);
}
};
void visit(char &a)
{
cout<<a<<" ";
}
int main()
{
cout<<"please input the value of binary tree:";
BinaryTree<char> a;
cout<<"The result of Preorder: ";
a.PreOrder();cout<<endl;
cout<<"The result of Inorder: ";
a.InOrder();cout<<endl;
cout<<"The result of Postorder: ";
a.PostOrder();cout<<endl;
cout<<"Node count: "<<a.NodeCount()<<endl;
cout<<"Tree hight: "<<a.Hight()<<endl;
cout << "Lips count: "<<a.Lip()<<endl;
return 0;
}
二 实例图片:
三 结果:
输入:ABD##E##CF##G##(想想为什么这么输入)
输出:
please input the value of binary tree:ABD##E##CF##G##
The result of Preorder: A B D E C F G
The result of Inorder: D B E A F C G
The result of Postorder: D E B F G C A
Node count: 7
Tree hight: 3
Lips count: 3