HeadMain.h
#include<iostream>
using namespace std;
#include"BTree.h"
BTree.h
struct TreeNode
{
char data;
TreeNode *left;
TreeNode *right;
TreeNode()
{
data=0;
left=NULL;
right=NULL;
}
};
class CBTree
{
public:
TreeNode *BT;
CBTree();
~CBTree();
void InitBTree(TreeNode *BT);
void CreateBTree( TreeNode *&BT,char * item);
bool IsEmptyBTree(TreeNode * BT);
int DepthBTree(TreeNode *BT);
bool FindBTree(TreeNode * BT ,int &item);
void PrintBTree(TreeNode *BT);
void ClearBTree(TreeNode *BT);
void PreOrder(TreeNode *BT);
};
BTree.cpp
#include"HeadMain.h"
/*
通过广义表表示树的结果的链接储存的实现
A(B(E,F),D(E),G)
*/
CBTree::CBTree()
{
BT=NULL;
}
CBTree::~CBTree()
{
delete BT;
}
void CBTree::InitBTree(TreeNode *BT)
{
BT=NULL;
}
void CBTree::CreateBTree(TreeNode *&BT,char* a)
{
const int MaxSize=10;
TreeNode *s[MaxSize];
int i=0;
int top=-1;
BT=NULL;
TreeNode *p;
int k;
while(a[i])
{
switch(a[i])
{
case ' ':
break;
case '(':
if(top ==MaxSize-1)
{
cout<<"栈空间太小,请增加Maxsize的值"<<endl;
exit(1);
}
top++;
s[top]=p;
k=1;
break;
case ')':
if(top==-1)
{
cout<<"二叉树广义表定义错误!"<<endl;
exit(1);
}
top--;
break;
case ',':
k=2;
break;
default:
p= new TreeNode();
p->data=a[i];
if(BT==NULL)
{
BT=p;
}
else
{
if(k==1)
{
s[top]->left=p;
}
else s[top]->right=p;
}
}
i++;
}
}
bool CBTree::IsEmptyBTree(TreeNode * BT)
{
if(BT==NULL)
return true;
return false;
}
int CBTree::DepthBTree(TreeNode *BT)
{
//if(BT==NULL)
//return 0;
//else
//{
// int dep1=DepthBTree(BT->left);
// int dep2=DepthBTree(BT->right);
// if(dep1>dep2)
// {
// return dep1+1;
// }
// else
// {
// return dep2+1;
// }
//}
TreeNode *temp=BT;
int i=0;
int j=0;
while(temp!=NULL)
{
temp=temp->left;
i++;
}
TreeNode *temp1=BT;
while(temp1!=NULL)
{
temp1=temp1->right;
j++;
}
if(i>j)
return i;
return j;
}
bool CBTree::FindBTree(TreeNode * BT ,int &x)
{
if(BT==NULL)
{
return false;
}
else
{
if(BT->data==x)
{
x=BT->data;return true;
}
else
{
if(FindBTree(BT->left,x))return true;
if(FindBTree(BT->right,x))return true;
return false;
}
}
return true;
}
void CBTree::PrintBTree(TreeNode *BT)
{
if(BT!=NULL)
{
cout<<BT->data<<" ";
if(BT->left!=NULL || BT->right!=NULL)
{
cout<<'(';
PrintBTree(BT->left);
if(BT->right!=NULL)
cout<<',';
PrintBTree(BT->right);
cout<<')';
}
}
}
void CBTree::PreOrder(TreeNode *BT)
{ cout<<endl;
if(BT!=NULL)
{
cout<<BT->data<<" ";
PrintBTree(BT->left);
PrintBTree(BT->right);
}
}
void CBTree::ClearBTree(TreeNode *BT)
{
if(BT!=NULL)
{
ClearBTree(BT->left);
ClearBTree(BT->right);
delete BT;
BT=NULL;
}
}
main.cpp
#include"HeadMain.h"
void main()
{
char b[20];
TreeNode *BT=NULL;
CBTree *tree = new CBTree();
tree->InitBTree(BT);
cin.getline(b,sizeof(b));
tree->CreateBTree(BT,b);
tree->PrintBTree(BT);
cout<<endl;
cout<<tree->DepthBTree(BT);
tree->PreOrder(BT);
}