通过C++模板编程实现二叉搜索树。代码如下:
#include <iostream>
#include<stack>
using namespace std;
template <class T>
class BinarySearchTree;
template <class T>
class BinarySearchTreeNode {
friend class BinarySearchTree<T>;
private:
T element;
BinarySearchTreeNode<T>* leftChild;
BinarySearchTreeNode<T>* rightChild;
public:
BinarySearchTreeNode();
BinarySearchTreeNode(const T& ele)
{
element = ele;
leftChild = NULL;
rightChild = NULL;
}
BinarySearchTreeNode(const T& ele, BinarySearchTreeNode<T>* l, BinarySearchTreeNode<T>* r)
{
element = ele;
leftChild = l;
rightChild = r;
}
BinarySearchTreeNode<T>* getLeftChild() const
{
return leftChild;
}
BinarySearchTreeNode<T>* getRightChild() const
{
return rightChild;
}
void setLeftChild(BinarySearchTreeNode<T>* l)
{
leftChild = l;
}
void setRightChild(BinarySearchTreeNode<T>* r)
{
rightChild = r;
}
T getValue() const
{
return element;
}
void setValue(const T& val)
{
element = val;
}
bool isLeaf() const
{
if (leftChild == NULL && rightChild == NULL)
return true;
return false;