本篇文章使用c++描述普通二叉树的遍历操作
代码详见:https://github.com/rebelsisyphus/vscode/blob/main/.vscode/data%20structure/Bintree/tree.h
二叉树存储结构
使用链式存储结构
template <class T>
struct BinTreeNode{
T data;
int height;
BinTreeNode<T> *leftChild,*rightChild;
BinTreeNode():leftChild(NULL),rightChild(NULL),height(-1){
};
BinTreeNode(T x,BinTreeNode<T> *l=NULL,BinTreeNode<T> *r=NULL){
data=x;
leftChild=l;
rightChild=r;
height=0;
}
};
二叉树类
二叉树类,实现二叉树的建造,求树高/元素数,四种遍历方式,不进行插入删除操作
若遍历函数使用递归实现,那么形参需要二叉树与visit函数,root需要作为形参,
而考虑到程序的封装性,我们并不希望主函数可以直接访问数据
因此将递归函数设置为保护成员,在公有函数中设置接口,调用递归函数,visit函数可以由主函数提供
增强其封装性
/*************************************************************************
二叉树类,实现二叉树的建造,求树高/元素数,四种遍历方式,不进行插入删除操作
***********************************************************************/
template <class T>
class BinTree{
protected:
BinTreeNode<T> *root;
void deleteall(BinTreeNode<T> *subtree);
int getheight(BinTreeNode<T> *subtree); //树高
int getsize(BinTreeNode<T> *subtree); //树内元素数
void Inorder(BinTreeNode<T> *subtree,void (*visit)(BinTreeNode<T> *s)); //中序遍历
void Preorder(BinTreeNode<T> *subtree,void (*visit)(BinTreeNode<T> *s)); //前序遍历
void Postorder(BinTreeNode<T> *subtree,void (*visit)(BinTreeNode<T> *s)); //后序遍历
void Levelorder(BinTreeNode<T> *subtree,void (*visit)(BinTreeNode<T> *s)); //层序遍历
/************************************************************************
若遍历函数使用递归实现,那么形参需要二叉树与visit函数,root需要作为形参,
而考虑到程序的封装性,我们并不希望主函数可以直接访问数据
因此我们将递归函数设置为私有,在公有函数中设置接口,调用递归函数,visit函数可以由主函数提供
增强其封装性
***********************************************************************/
public:
BinTree