递归二叉树建立、遍历、删除、打印

来源:互联网 发布:数据库中substring 编辑:程序博客网 时间:2024/06/05 07:09
#include "stdafx.h"#include <iostream>using namespace std;char value='A';class Data{public:Data(char* nameT):name(new char[2]){name[0]=*nameT;name[1]='\0';}ostream& operator>>(ostream& os){return os<<name;}~Data(){delete[] name;}char* name;};class Base{public://Base(){}Base(Base* p):Root(p){}virtual void* CreateRoot(void* data)=0;virtual void* CreateLeft(void* data)=0;virtual void* CreateRight(void* data)=0;friend class Data;Base* Root;};class Example:public Base{public://Example():Base(NULL){};Example(void* ObjTempT=NULL):Left(NULL),Right(NULL),ObjTemp(ObjTempT),Base(NULL){}~Example(){clear((Example*)Root);Root=NULL;}void* CreateRoot(void* data){if(Root == NULL)throw Uniqueness();
return Root = new Example(data);}void* CreateLeft(void* data){return  Left= new Example(data);}void* CreateRight(void* data){return Right = new Example(data);}    void travel(Example* obj)    {  if(obj==NULL)return;      (*((Data*)(obj->ObjTemp)))>>cout<<' '; travel(obj->Left);travel(obj->Right);}  void travel()  {     travel((Example*)Root);  cout<<endl;}void clear(Example* obj){if(obj==NULL)return;clear(obj->Left);obj->Left=NULL;clear(obj->Right);obj->Right=NULL;delete obj;}Example* Left;Example* Right;void* ObjTemp;};void BuildTree(void* point,int rcs){if(rcs<4){BuildTree(((Base*)point)->CreateLeft(new Data(&(++value))),rcs+1);BuildTree(((Base*)point)->CreateRight(new Data(&(++value))),rcs+1);}}int main(){Example obj(NULL);Base* execute = &obj;BuildTree(execute->CreateRoot(new Data(&value)),1);     obj.travel();       return 0;}