#include<iostream>
using namespace std;
struct tree{
int data;
tree *left,*right;
};
typedef tree* mytree;
class Btree{
public:
mytree root;
Btree()
{
root=NULL;
}
mytree creat(mytree,int);//创建二叉排序树
mytree copy(mytree);//复制二叉树
void preOrder(mytree);//前序遍历
void inOrder(mytree);//中序遍历
void postOrder(mytree);//后序遍历
void release(mytree);//删除二叉树
int getNum(mytree);//获取二叉树结点
};
mytree Btree::creat(mytree p,int x)
{
if(p==NULL)
{
p=new tree;
p->data =x;
p->left =p->right =NULL;
}
else if(x >p->data )
p->right =creat(p->right ,x);
else if(x <p->data )
p->left =creat(p->left ,x);
else
;
return p;
}
void Btree::preOrder(mytree t)
{
if(t!=NULL)
{
cout<<t->data<<" " ;
inOrder(t->left );
inOrder(t->right );
}
}
void Btree::inOrder(mytree t)
{
if(t!=NULL)
{
inOrder(t->left );
cout<<t->data<<" ";
inOrder(t->right );
}
}
void Btree::postOrder(mytree t)
{
if(t!=NULL)
{
postOrder(t->left );
postOrder(t->right );
cout<<t->data<<" " ;
}
}
mytree Btree::copy(mytree p)
{
mytree newTree;
if(p==NULL)
newTree=NULL;
else
{
newTree=new tree;
newTree->data =p->data ;
newTree->left =copy(p->left );
newTree->right =copy(p->right );
}
return newTree;
}
void Btree::release(mytree p)
{
if(p!=NULL)
{
release(p->left );
release(p->right);
delete p;
}
}
int Btree::getNum(mytree p)
{
if(p==NULL)
return 0;
int lefts=0,rights=0;
if(p->left!=NULL)
lefts=getNum(p->left);
if(p->right!=NULL)
rights=getNum(p->right);
return lefts+rights+1;
}
int main()
{
Btree BST;
int temp;
cout<<"请输入要加入的结点"<<endl;
while(cin>>temp){
BST.root=BST.creat(BST.root,temp);
}
BST.inOrder(BST.root);
cout<<endl;
mytree p;
p=BST.copy(BST.root) ;
BST.inOrder(p);
cout<<endl;
cout<<BST.getNum(BST.root );
}
C++ 二叉排序树基本操作1
最新推荐文章于 2022-11-11 19:21:51 发布