BinaryTree.h源文件
#pragma once
#include<iostream>
using namespace std;
template<class T>
struct BinTreeNode //二叉树结点类定义
{
T _data; //存放数据
BinTreeNode<T>* _pleftChild, *_prightChild; //指向左右子女得指针
//默认构造函数,将指针指向空
BinTreeNode() :_pleftChild(nullptr),
_prightChild(nullptr) {}
//
BinTreeNode(T d, BinTreeNode<T>* l = nullptr,
BinTreeNode<T>* r = nullptr) :_data(d), _pleftChild(l),
_prightChild(r) {}
};
template<class T>
class BinaryTree { //二叉树类定义
public:
BinaryTree() :_pRoot(nullptr) {} //构造函数
BinaryTree(T ref) :refValue(ref), _pRoot(nullptr) {} //构造函数,指定结束标志
BinaryTree(BinaryTree<T>& copyTree); //复制构造函数
void operator = (BinaryTree<T>& copyTree); //重载赋值运算符
~BinaryTree() { destroy(_pRoot); } //析构函数
bool isEmpty() { return(_pRoot == nullptr) ? true : false; }//判断二叉树是否为空
void setRefValue(T ref) { refValue = ref; } //设置树输入结束标志
T getRefValue() { return refValue; } //设置树输入结束标志
BinTreeNode<T>* parent(BinTreeNode<T>* curTree) { //获取父节点函数
return (_pRoot == nullptr || _pRoot == curTree)
? nullptr : getParent(_pRoot, curTree);
}
BinTreeNode<T>* leftChild(BinTreeNode<T>* curTree) { //获取左孩子
return(curTree->_pleftChild == nullptr) ? nullptr: curTree->_pleftChild;
}
BinTreeNode<T>* rightChild(BinTreeNode<T>* curTree) { //获取有孩子
return(curTree->_prightChild == nullptr) ? nullptr : curTree->_prightChild;
}
int height() const { return height(_pRoot); } //获取树的高度
int size() const { return size(_pRoot); } //返回结点数量
BinTreeNode<T>* getRoot() const { return _pRoot; } //返回根节点
void preOrder(/*void(*visit)(BinTreeNode<T>* p)*/){ //前序遍历
preOrder(_pRoot);
}
void inOrder(/*void(*visit)(BinTreeNode<T>* p)*/) { //中序遍历
inOrder(_pRoot);
}
void postOrder(/*void(*visit)(BinTreeNode<T>* p)*/) { //后序遍历
postOrder(_pRoot);
}
bool insert(BinTreeNode<T>* &subTree, const T& data, bool l = true); //插入结点函数
BinTreeNode<T>* find(const T& data)const; //搜索
//因为友元不是授权类的成员,
//所以它不受其所在类的声明区域public private 和protected 的影响。
friend istream& operator >> (istream& in, BinaryTree<T> &tree) { //重载输入操作
cout << "请输入一个二叉树,子树以" << tree.getRefValue() << "结尾" << endl;
//BinTreeNode<T> *pRoot = tree.getRoot();
tree.createBinTree(in, tree._pRoot); //直接函数的调用,默认前序输入
return in;
}
friend ostream& operator << (ostream& out, const BinaryTree<T>& tree) { //重载输出操作
//BinTreeNode<T>* subTree = tree.getRoot();
tree.Traverse(tree._pRoot, out); //直接调用前序遍历函数
return out; //返回输出流
}
bool operator == (BinaryTree<T>& subTree); //重载“==”运算符
private:
BinTreeNode <T>* _pRoot; //存放根节点
T refValue; //数据输入退出标志
void createBinTree(ist