#include <iostream>
using namespace std;
template <class T> class BST;
template <class T>
class Element
{
public :
T key;
};
template <class T>
class BstNode
{
friend class BST<T>;
public:
//private:
Element<T> data;
BstNode * leftChild;
BstNode * rightChild;
void display(int i);
};
template <class T>
class BST
{
public:
BST(BstNode<T>* init = 0) :root(init) {}
bool Insert(Element<T> const &x); //二叉查找树插入节点
BstNode<T>* Search(Element<T> const &x); //二叉查找树递归查找节点
BstNode<T>* Search(BstNode<T>*, Element<T> const &x);
BstNode<T>* IterSearch(Element<T> const &x); //
void display()
{
cout << "\n";
if (root)
root->display(1);
else
cout << "empty tree\n";
}
private:
BstNode<T> * root;
};
template<class T>
void BstNode<T>::display(int i)
{
cout << "Position:" << i << ":data.key:" << data.key << "\n";
if (leftChild) leftChild->display(2*i); //左边的是2*i
if (rightChild) rightChild->display(2*i+1); //右边的是2*i +1
}
template <class T>
bool BST<T>::Insert(Element<T> const &x)
{
BstNode<T> *p = root;
BstNode<T> *q = p;
while (p)
{
q = p;
if (x.key == p->data.key)
{
cout << "already in tree" << endl;
return false;
}
else if (x.key < p->data.key)
p = p->leftChild;
else if (x.key > p->data.key)
p = p->rightChild;
}
//找到的位置的上个节点就是q,下个节点就是p,p是q的子节点
p = new BstNode<T>;
p->data = x;
p->leftChild = p->rightChild = 0;
if (root == 0) root = p;
else if (q->data.key > x.key) q->leftChild = p;
else if (q->data.key < x.key) q->rightChild = p;
return true;
}
template <class T>
BstNode<T>* BST<T>::Search(Element<T> const &x)
{
return Search(root,x);
}
template <class T>
BstNode<T>* BST<T>::Search(BstNode<T>* node, Element<T> const & ele)
{
if (node == 0) return 0;
if (node->data.key == ele.key) return node;
if (node->data.key < ele.key) return Search(node->rightChild,ele);
else return Search(node->leftChild,ele);
}
template <class T>
BstNode<T>* BST<T>::IterSearch(Element<T> const &x)
{
for (BstNode<T>* p = root;p!= 0;)
{
if (p->data.key == x.key) return p;
if (p->data.key < x.key)
p = p->rightChild;
else
p = p->leftChild;
}
}
int main()
{
BST<int> bst;
Element<int> a, b, c, d, e, f, g, h, i, j, k, l;
a.key = 5;
b.key = 3;
c.key = 11;
d.key = 3;
e.key = 15;
f.key = 2;
g.key = 8;
h.key = 22;
i.key = 20;
j.key = 9;
cout<<bst.Insert(a)<<endl;
cout << bst.Insert(b)<<endl;
cout << bst.Insert(c)<<endl;
cout << bst.Insert(d) << endl;
cout << bst.Insert(e) << endl;
cout << bst.Insert(f) << endl;
cout << bst.Insert(g) << endl;
cout << bst.Insert(h) << endl;
cout << bst.Insert(i) << endl;
cout << bst.Insert(j) << endl;
bst.display();
BstNode<int>* p = bst.Search(c);
if (p != 0)
{
cout << "Search 找到了:" << p->data.key << endl;
}
else
{
cout << "Search 没找到" << endl;
}
p = bst.IterSearch(c);
if (p != 0)
{
cout << "IterSearch 找到了:" << p->data.key << endl;
}
else
{
cout << "IterSearch 没找到" << endl;
}
return 0;
}
operation result: