#include<iostream>
#include<string>using namespace std;
//构建二叉树的结构体
template< typename T>
struct binaryTreeNode
{T element; //数据binaryTreeNode<T>* leftChild; //左子树指针binaryTreeNode<T>* rightChild; //右子树指针//C C++ 区别//无参数构造函数-->用来给数据初始化binaryTreeNode(){leftChild = rightChild = NULL;}//传入数据域//C++初始化参数列表(const数据域必须采用这种方式)binaryTreeNode(const T& element) :element(element){leftChild = rightChild = NULL;}//C++类中const成员: const数据成员 const成员函数binaryTreeNode(const T& element, binaryTreeNode<T> * leftChild, binaryTreeNode<T>* rightChild) :element(element){//c++ thisthis->leftChild = leftChild;this->rightChild = rightChild;}};template< typename K, typename E>
class binarySearchTree {
public:binarySearchTree();//万金油函数:判断是否为空+size大小+打印数据int size() const; //const 成员函数里面不能修改基本数据成员bool empty() const;void printNode(binaryTreeNode<pair<const K, E>>* Node);void visit(binaryTreeNode<pair<const K, E>>* Node){cout << Node->element.first << ":" << Node->element.second << endl;}void printTree();//插入结点:插入的pair类型的结构体数据void insert(const pair<const K, E> &thePair);//删除结点:根据关键字删除//void erase(const K& theKey);//查找结点//pair<const &K, E>* find(const K& theKey);
protected: //pair<const K,E> 模板结构体名binaryTreeNode<pair<const K, E>>* root;//根结点表示整个数int treeSize; //记录结点数
};template< typename K, typename E>
int binarySearchTree<K,E>::size() const
{return treeSize;
}template< typename K, typename E>
bool binarySearchTree <K,E>::empty() const
{return treeSize == 0;
}template< typename K, typename E>
binarySearchTree <K, E>::binarySearchTree()
{root = NULL;treeSize = 0;
}template<typename K, typename E>
void binarySearchTree<K, E>::printNode(binaryTreeNode<pair<const K, E>>* Node)
{if (Node != NULL){printNode(Node->leftChild);visit(Node);printNode(Node->rightChild);}
}
template<typename K, typename E>
void binarySearchTree<K, E>::printTree()
{printNode(root);
}template<typename K,typename E>
void binarySearchTree <K, E>::insert(const pair<const K, E> & thePair)
{//找到合适的位置插入binaryTreeNode<pair<const K, E>> *p = root;binaryTreeNode<pair<const K, E>> *pp = NULL;while (p != NULL){pp = p; //记录父结点if (thePair.first < p->element.first){p = p->leftChild;}else if (thePair.first > p->element.first){p = p->rightChild;}else { //表示键存在p->element.second = thePair.second;return;}}binaryTreeNode<pair<const K, E>>* newNode = new binaryTreeNode<pair<const K, E>>(thePair);if (root != NULL){if (thePair.first < pp->element.first){pp->leftChild = newNode;}else pp->rightChild = newNode;}else{root = newNode;}treeSize++;
}int main()
{binarySearchTree<int, string> myBST;myBST.insert(pair<int, string>(8, "美丽世界"));myBST.insert(pair<int, string>(9, "343434"));myBST.insert(pair<int, string>(5, "Joken"));myBST.insert(pair<int, string>(1, "VICO"));myBST.insert(pair<int, string>(6, "widget"));myBST.insert(pair<int, string>(2, "nana"));myBST.printTree();system("pause");return 0;
}
运行结果: