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);
}
二叉树的抽象数据类型代码实现(C++)
最新推荐文章于 2022-06-06 14:23:40 发布
本文详细介绍了如何使用C++编程语言实现二叉树的抽象数据类型(ADT),包括插入、删除、遍历等基本操作,旨在帮助读者深入理解二叉树的数据结构及其操作。
691

被折叠的 条评论
为什么被折叠?



