二叉树的抽象数据类型代码实现(C++)

本文详细介绍了如何使用C++编程语言实现二叉树的抽象数据类型(ADT),包括插入、删除、遍历等基本操作,旨在帮助读者深入理解二叉树的数据结构及其操作。
typedef  int  DataType
Class BinTreeNode {
public:
    DataType data;
    BinTreeNode  * leftChild;
    BinTreeNode  * rightChild;
    BinTreeNode( ){leftChild=NULL; rightChild=NULL; }
                                      //构造函数,构造一个空结点
};
class BinaryTree {
public:
BinTreeNode  *root;
BinaryTree(){root=NULL; }BinaryTree(){DeleteTree(); }
bool InsertLeft(BinTreeNode * current, DataType  x);
                              //将元素x插入作为current所指结点的左孩子
bool InsertRight(BinTreeNode * current, DataType  x);
//将元素x插入作为current所指结点的右孩子

void Preorder(BinTreeNode  *current);       //先序遍历
void InOrder(BinTreeNode *current);        //中序遍历
void Postorder(BinTreeNode *current);      //后序遍历
BinTreeNode * Find(BinTreeNode *current, DataType x);
                                        //搜索值为x的结点
void Destroy(BinTreeNode * current);       //删除指定子树
void DeleteTree(){Destroy(root); root=NULL; }//删除整棵树
bool IsEmpty( ){ return root == NULL }     //判树空否
BinTreeNode  *CreatBinTree() ;              //创建一棵二叉树
};
2.二叉树部分成员函数的实现

bool  BinaryTree:: InsertLeft(BinTreeNode * current, DataType  item)
                                          //插入左孩子
{
  if(current==NULL)return false;
  BinTreeNode *p=new BinTreeNode;
  p->data=item;
  current->leftChild=p;
  return true;
}
bool  BinaryTree:: InsertRight(BinTreeNode * current, DataType  item)
                                          //插入右孩子
{
  if(current==NULL)return false;
  BinTreeNode *p=new BinTreeNode;
  p->data=item;
  current->rightChild=p;
  return true;
}
void BinaryTree :: destroy(BinTreeNode *current)
                                          //删除指定子树
{
    if(current ! = NULL){
        destroy(current -> leftChild);
        destroy(current -> rightChild);
        delete current;
    }
}
BinTreeNode  * BinaryTree :: Find(BinTreeNode *current, DataType x)
                                          //搜索值为x的结点
{
if(current==NULL)return NULL;
if(current->data==x)return current;
BinTreeNode *p=Find(current->leftChild);
if(p! =NULL)
return p;
else
return Find(current->rightChild);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值