C++模板实现二叉树

这篇博客介绍了如何使用C++模板实现二叉树,包括清空、查找、插入、移除节点以及前序、中序、后序遍历等功能。通过BinaryTree类和BTnode类的详细定义,展示了构造函数、析构函数、赋值重载函数等的实现,并提供了main函数的测试代码。
摘要由CSDN通过智能技术生成

Github完整代码下载地址

完整头文件在项目的路径为:inc/chapter6.h

BinaryTree 类定义

BinaryTree类实现的二叉树能够实现以下功能:

  • 清空二叉树
  • 查找
  • 插入
  • 移除
  • 前序(preorder),中序(inorder),后序(postorder)的方式遍历整个二叉树
template <typename elemType>
class BinaryTree{
    friend class BTnode<elemType>;
public:
    BinaryTree();
    BinaryTree( const BinaryTree& );
    ~BinaryTree();

    BinaryTree& operator=( const BinaryTree& );  //这里只是一个声明,需要在其他地方定义这个函数

    bool empty() { return _root == 0; }
    void clear() { if( _root ){ clear( _root ); _root = 0; } }
    
    bool find( const elemType& ) const;
    void insert( const elemType & );
    void remove( const elemType & );

    void inorder( ostream &os = *_current_os )   const { _root->inorder( _root, os ); }
    void postorder( ostream &os = *_current_os ) const { _root->postorder( _root, os ); }
    void preorder( ostream &os = *_current_os )  const { _root->preorder( _root, os ); }

    ostream& print( ostream &os = *_current_os, 
                    void (BinaryTree<elemType>::*traversal)( ostream& ) const = 				     		                               &BinaryTree<elemType>::preorder) const;

    static void current_os( ostream *os = &cout ) {  if(os) {_current_os = os;} }  // 注意这里是 &cout
    static ostream* os() { return _current_os; }
    
private:
    BTnode<elemType> *_root;
    static ostream *_current_os; // 还需要在其他地方定义一下,是不是所有的static都是要在class外定义一下

    void clear( BTnode<elemType>* );
    void copy( BTnode<elemType>*tar, BTnode<elemType>*src );
    void remove_root(); 
};

因为在C++中,类的静态成员(static member)必须在类内声明,在类外初始化,所以在BinaryTree类中,_current_os需要在类外进行初始化,实现代码如下:

template <typename elemType>
ostream *BinaryTree<ele
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值