概念:
二叉搜索树:又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树
1、若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
2、若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
3、它的左右子树也分别为二叉搜索树
/*
* 说明1:这篇博客介绍的是二叉搜索树所有操作(除了删除)的非递归写法。
*下一篇博客介绍,二叉搜索树的递归写法,和删除操作。
*
* 说明2:之所以分开写删除,是因为删除比较麻烦也是重点。
*/
#include
using namespace std;
typedef struct TreeNode
{
int key;
int data;
struct TreeNode* pleft;
struct TreeNode* pright;
}TreeNode, *pTreeNode;
pTreeNode new_node(int key, int value)
{
pTreeNode temp = (pTreeNode)malloc(sizeof(TreeNode));
temp->data = value;
temp->key = key;
temp->pleft = NULL;
temp->pright = NULL;
return temp;
}
class BinarySeachTree
{
public:
BinarySeachTree()
:proot(NULL)
{}
BinarySeachTree(const BinarySeachTree& d)
{
proot = _BinarySeachTree(d.proot);
}
BinarySeachTree& operator=(BinarySeachTree& s)
{
if (this != &s)
{
clear(proot);
proot = _BinarySeachTree(s.proot);
}
return *this;
}
~BinarySeachTree()
{
clear(proot);
}
//查找
bool find(int _key)
{
return _find(proot, _key);
}
//判空
bool Empty()const
{
return proot == NULL;
}
private:
pTreeNode _BinarySeachTree(pTreeNode proot)
{
pTreeNode temp = NULL;
if (proot != NULL)
{
temp = new_node(proot->key, proot->data);
temp->pleft = _BinarySeachTree(temp->pleft);
temp->pright = _BinarySeachTree(temp->pright);
}
return temp;
}
public:
void Insert_node(int key, int value)
{
pTreeNode temp = new_node(key, value);
if (proot == NULL)
{
proot = temp;
}
else
{
pTreeNode flag = proot;
pTreeNode pro = proot;
while(flag)
{
if(NULL != flag && temp->key > flag->key)
{
pro = flag;
flag = flag->pright;
}
if(NULL != flag && temp->key < flag->key)
{
pro = flag;
flag = flag->pleft;
}
}
if(temp->key < pro->key)
pro->pleft = temp;
if(temp->key > pro->key)
pro->pright = temp;
}
}
private:
//查找
bool _find(pTreeNode proot, int _key)
{
if (proot == NULL)
{
return false;
}
while(proot)
{
if (NULL != proot && proot->key == _key)
{
return true;
}
else if (NULL != proot && proot->key < _key)
{
proot = proot->pright;
}
else if (NULL != proot && proot->key > _key)
{
proot = proot->pleft;
}
}
return false;
}
void clear(pTreeNode& proot)
{
if (proot != NULL)
{
clear(proot->pleft);
clear(proot->pright);
free(proot);
proot = NULL;
}
}
private:
pTreeNode proot;
};
int main()
{
BinarySeachTree t, t1;
t.Insert_node(5,5);
t.Insert_node(3,3);
t.Insert_node(4,4);
t.Insert_node(1,1);
t.Insert_node(7,7);
t.Insert_node(8,8);
t.Insert_node(2,2);
t.Insert_node(6,6);
t.Insert_node(0,0);
t.Insert_node(9,9);
//cout<
<
如有错误欢迎指正。