二叉树搜索的性质
非空二叉搜索树具有以下性质:
1)若左子树不为空,则左子树所有结点的值均小于或等于它根节点的值;
2)若右子树不为空,则右子树所有结点的值均大于或等于它根节点的值;
3)它的左右子树也是一颗二叉搜索树(空树也是二叉搜索树)
4)中序遍历为递增序列( 元素不重复)
如图:
二叉搜索树的数据结构
这里树结点的值以int举例
struct node {
node(int x = 0) :val(x), left(nullptr), right(nullptr) {}
int val;
node* left;
node* right;
void show(){ //中序遍历
if (this != nullptr) {
this->left->show();
cout << this->val<< " ";
this->right->show();
}
}
};
class BST {
node* root;
public:
BST() :root(nullptr){ }
bool query(int x);
void insert(int x);
void show() {
root->show();
cout << endl;
}
};
二叉搜索树的查询
以根节点为当前节点开始查找
)若当前节点为空,返回false;
)若当前节点的值等于要查找的值,返回true;
)若当前节点的值小于要查找的值,当前节点更新为当前节点的右节点;
)若当前节点的值大于要查找的值,当前节点更新为当前节点的左节点;
假如我们要查找4,从根节点6开始找,4 < 6,当前节点更新为3,4 > 3,当前节点更新为4,4 = 4,return true;
查找5,从根节点6开始找,5 < 6,当前节点更新为3,5> 3,当前节点更新为4,5 > 4,4的右子树为空,当前节点更新为空, return false;
bool BST::query(int x) {
if (root == nullptr) return false;
node* p = root;
while (p != nullptr) {
if (p->val == x) return true;
else if (p->val > x) p = p->left;
else if (p->val < x) p = p->right;
}
return false;
}
二叉搜索树的插入
插入操作跟查询操作类似
)若根结点为空,把根节点指向新节点,插入完成
若根结点不为空,以根结点为当前节点,找到要插入的位置
)若当前节点的值小于要插入结点的值,若左结点为空,令当前结点的左结点指向新节点,插入完成;若左结点不为空,当前结点更新为当前结点的左结点;
)若当前节点的值大于要插入结点的值,若右结点为空,令当前结点的右结点指向新节点,插入完成;若右结点不为空,当前结点更新为当前结点的右结点;
void BST::insert(int x)
{
if (root == nullptr) {
root = new node(x);
return;
}
node* newnode = new node(x);
node* p = root;
while (p != nullptr)
{
if (x < p->val)
{
if (p->left == nullptr) {
p->left = newnode;
return;
}
p = p->left;
}
else {
if (p->right == nullptr) {
p->right = newnode;
return;
}
p = p->right;
}
}
}
二叉搜索树的验证
#include <iostream>
#include <vector>
using namespace std;
struct node {
node(int x = 0) :val(x), left(nullptr), right(nullptr) {}
int val;
node* left;
node* right;
void show() {
if (this != nullptr) {
this->left->show();
cout << this->val<< " ";
this->right->show();
}
}
};
class BST {
node* root;
public:
BST() :root(nullptr){ }
void insert(int x){
if (root == nullptr) {
root = new node(x);
return;
}
node* newnode = new node(x);
node* p = root;
while (p != nullptr){
if (x < p->val){
if (p->left == nullptr) {
p->left = newnode;
return;
}
p = p->left;
}
else {
if (p->right == nullptr) {
p->right = newnode;
return;
}
p = p->right;
}
}
}
void show() {
root->show();
cout << endl;
}
bool query(int x) {
if (root == nullptr) return false;
node* p = root;
while (p != nullptr) {
if (p->val == x) return true;
else if (p->val > x) p = p->left;
else if (p->val < x) p = p->right;
}
return false;
}
};
void testNums(vector<int>& v) {
for (int i = 0; i < 100; i++) {
v.push_back(rand() % 100);
}
}
int main()
{
BST* t = new BST;
vector<int> v;
testNums(v);
for (int i = 0; i < 100; i++) {
cout << v[i] << " ";
}
cout << endl;
for (int i = 0; i < 100; i++) {
t->insert(v[i]);
}
t->show();
cout << "11::" << t->query(11) << endl;
cout << "13::" << t->query(13) << endl;
cout << "15::" << t->query(15) << endl;
cout << "21::" << t->query(21) << endl;
cout << "31::" << t->query(31) << endl;
}