完整头文件在项目的路径为: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