#include<iostream>
using namespace std;
//前置声明
class tree;
//节点:
class node
{
public:
friend class tree;
node(char);
protected:
char data;//数据域
node* lchild;//指向左孩子
node* rchild;//指向右孩子
};
node::node(char d):data(d),lchild(NULL),rchild(NULL){}
//树
class tree
{
public:
tree();
bool createTree(char*&,node*&);//地址 地址变量引用
node*& getRoot();//定义公有接口
//遍历 前序 中序 后序
//前序:
void preOrder(node*);//前序
void inOrder(node*);//中序
void postOrder(node*);//后序
//查找
node* find(node*,char);
node* match(char key,node* ploc);//判断ploc节点是否在存在key值
bool alter(char key,node* ploc,char vaule);//修改
protected:
node* root;//根节点---堆区
};
tree::tree():root(NULL)
{
}
//判断ploc节点是否存在key值,存在返回该节点地址 不存在则遍历查找
node* tree::match(char key,node* ploc)
{
node* result=NULL;
if(NULL==ploc)
return NULL;
if(key==ploc->data)
return ploc;
//左子树
result=match(key,ploc->lchild); //返回地址 或 NULL
if(result!=NULL)
return result;
//右子树
return match(key,ploc->rchild);
}
bool tree:: alter(char key,node* ploc,char value)//修改
{
node* result=NULL;
result=this->match(key,ploc);
if(NULL!=result)
{
result->data=value;
return true;
}
else
return false;
}
//查找
node* tree:: find(node* ploc,char key)
{
node* result=NULL;
if(NULL==ploc)
return result;
if(ploc->data==key)
return ploc;
//左子树
if(NULL!=(result=find(ploc->lchild,key)))
return result;
//右子树
if(NULL!=(result=find(ploc->rchild,key)))
return result;
}
//前序遍历:每次调用函数时只打印当前节点信息,左子树/右子树交给下一次函数来打印
void tree::preOrder(node* ploc)
{
if(NULL==ploc)
return;
//只打印ploc节点的信息
cout<<ploc->data<<" ";
//左子树的节点
preOrder(ploc->lchild);//递归打印左子树的节点
preOrder(ploc->rchild);//递归打印右子树的节点
}
//前序创建树
bool tree::createTree(char* &d,node* &ploc)
{
if('\0'==*d)
return true;
//1分配节点空间
if('#'==*d)//当前节点为空节点
ploc=NULL;
else
{
ploc=new node(*d);//new对象---由构造器分配空间
if(NULL==ploc)
return false;
//2修改指针向域
createTree(++d,ploc->lchild);//当前节点的左子树
createTree(++d,ploc->rchild);//当前节点的右子树
return true;
}
}
void tree:: postOrder(node* ploc)//后序
{
if(NULL==ploc)
return;
//遍历左子树
postOrder(ploc->lchild);
//遍历右子树
postOrder(ploc->rchild);
//访问当前节点
cout<<ploc->data<<" ";
}
void tree::inOrder(node* ploc)
{
if(NULL==ploc)
return;
//遍历左子树
inOrder(ploc->lchild);
//打印当前节点
cout<<ploc->data<<" ";
//遍历右子树
inOrder(ploc->rchild);
}
node* &tree::getRoot()
{
return this->root;
}
int main()
{
char *buf="a#bc##d##";
//实例化
tree t;//构造器
t.createTree(buf,t.getRoot());
t.preOrder(t.getRoot());
cout<<endl;
t.inOrder(t.getRoot());
cout<<endl;
t.postOrder(t.getRoot());
cout<<endl;
if(NULL!=t.match('c',t.getRoot()))
cout<<"查找成功"<<endl;
else
cout<<"查找失败"<<endl;
t.alter('c',t.getRoot(),'Y');
t.preOrder(t.getRoot());
cout<<endl;
}