一、什么是二叉搜索树
二叉搜索树(Binary Search Tree)又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树: (1)若它的左子树不为空,则左子树上所有节点的值都小于根节点的值 (2)若它的右子树不为空,则右子树上所有节点的值都大于根节点的值 (3)它的左右子树也分别为二叉搜索树 二叉搜索树拥有很高的查找效率(一般情况下),树中最左节点为最小元素,最右节点为最大元素
二、二叉搜索树的实现(查找、插入、删除)
代码如下:
#include<iostream>
using namespace std
;
template
<class T
>
struct BSTNode
{
BSTNode
<T
>* left
;
BSTNode
<T
>* right
;
T _val
;
BSTNode(const T
& val
)
:left(nullptr
)
, right(nullptr
)
, _val(val
)
{}
};
template
<class T
>
class BSTree
{
public
:
typedef BSTNode
<T
> Node
;
typedef Node
* pNode
;
bool
find(const T
& val
)
{
pNode cur
= root
;
while (cur
)
{
if (cur
->_val
== val
)
return true
;
else if (cur
->_val
> val
)
cur
= cur
->left
;
else
cur
= cur
->right
;
}
return false
;
}
bool
insert(const T
& val
)
{
if (root
== nullptr
)
{
root
= new
Node(val
);
return true
;
}
pNode cur
= root
;
pNode parent
= nullptr
;
while (cur
)
{
parent
= cur
;
if (cur
->_val
== val
)
return false
;
else if (cur
->_val
> val
)
cur
= cur
->left
;
else
cur
= cur
->right
;
}
cur
= new
Node(val
);
if (parent
->_val
> val
)
parent
->left
= cur
;
else
parent
->right
= cur
;
return true
;
}
bool
erase(const T
& val
)
{
if (root
== nullptr
)
return false
;
pNode cur
= root
;
pNode parent
= nullptr
;
while (cur
)
{
if (cur
->_val
== val
)
break;
else if (cur
->_val
> val
)
{
parent
= cur
;
cur
= cur
->left
;
}
else
{
parent
= cur
;
cur
= cur
->right
;
}
}
if (cur
== nullptr
)
return false
;
else
{
if (cur
->left
== nullptr
)
{
if (cur
!= root
)
{
if (parent
->left
== cur
)
parent
->left
= cur
->right
;
else
parent
->right
= cur
->right
;
}
else
root
= cur
->right
;
delete cur
;
cur
= nullptr
;
}
else if (cur
->right
== nullptr
)
{
if (cur
!= root
)
{
if (parent
->left
== cur
)
parent
->left
= cur
->left
;
else
parent
->right
= cur
->left
;
}
else
root
= cur
->left
;
delete cur
;
cur
= nullptr
;
}
else
{
pNode next
= cur
->left
;
pNode parent
= cur
;
while (next
->right
)
{
parent
= next
;
next
= next
->right
;
}
cur
->_val
= next
->_val
;
if (parent
->left
== next
)
parent
->left
= next
->left
;
else
parent
->right
= next
->left
;
delete next
;
next
= nullptr
;
}
return true
;
}
}
void _inOrder(pNode root
)
{
if (root
)
{
_inOrder(root
->left
);
cout
<< root
->_val
<< " ";
_inOrder(root
->right
);
}
}
void inOrder()
{
_inOrder(root
);
cout
<< endl
;
}
private
:
pNode root
= nullptr
;
};
void testBSTree()
{
BSTree
<int> bst
;
bst
.insert(5);
bst
.insert(7);
bst
.insert(2);
bst
.insert(1);
bst
.insert(9);
bst
.insert(6);
bst
.insert(4);
bst
.insert(10);
bst
.insert(0);
bst
.inOrder();
bst
.erase(9);
bst
.erase(1);
bst
.erase(7);
bst
.inOrder();
}
int main()
{
testBSTree();
return 0;
}
运行截图:
二叉搜索树的中序遍历是一个递增的序列。
转载请注明原文地址:https://ipadbbs.8miu.com/read-19555.html