二叉查找樹的定義:
(1)要麼二叉查找樹是一顆空樹
(2)要麼二叉查找樹由根節點、左子樹、右子樹組成,其中左子樹和右子樹都是二叉查找樹,且左子樹上所有節點的數據域均小於或等於根節點的數據域,右子樹上所有節點的數據域均大於根節點的數據域。
基本操作接口:
1、建立樹節點結構體
2、節點的建立
3、二叉查找樹的建立
4、查找操作
5、插入操作
6、刪除操作
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
using namespace std;
// 節點的結構體
struct node
{
int data; // 數據域:可根據實際情況修改
node* lchild; // 左子樹
node* rchild; // 右子樹
};
// 節點的建立
node* newNode(int x)
{
node* root = new node;
root->data = x;
root->lchild = nullptr;
root->rchild = nullptr;
return root;
}
// 二叉查找樹的查找操作
void search(node* root, int x)
{
if (root == nullptr)
{
printf("not find\n");
return;
}
if (x == root->data)
printf("find it. %d\n", root->data);
else if (x < root->data)
search(root->lchild, x); // 往左子樹找
else
search(root->rchild, x); // 往右子樹找
}
// 二叉查找樹的插入操作
void insert(node*& root, int x)
{
if (root == nullptr)
{
root = newNode(x);
return;
}
if (x < root->data)
insert(root->lchild, x); // 往左子樹插入
else if (x > root->data)
insert(root->rchild, x); // 往右子樹插入
else
return; // 節點已存在
}
// 二叉查找樹的建立
node* create(vector<int> v)
{
node* root = nullptr;
int len = v.size();
for (int i = 0; i < len; ++i)
insert(root, v[i]);
return root;
}
// 找到以root爲根節點的樹中,權值最大的節點
node* findMax(node* root)
{
while (root->rchild != nullptr)
{
root = root->rchild;
}
return root;
}
// 找到以root爲根節點的樹中,權值最小的節點
node* findMin(node* root)
{
while (root->lchild != nullptr)
{
root = root->lchild;
}
return root;
}
// 二叉查找樹的刪除
void deleteNode(node*& root, int x)
{
if (root == nullptr) return;
if (root->data == x)
{
if (root->lchild == nullptr && root->rchild == nullptr)
root = nullptr;
else if (root->lchild != nullptr)
{
// 左子樹不爲空時,找到root的前驅節點,用前驅覆蓋root,然後在左子樹中刪除前驅節點
node* pre = findMax(root->lchild);
root->data = pre->data;
deleteNode(root->lchild, pre->data);
}
else if (root->rchild != nullptr)
{
// 右子樹不爲空時,找到root的後繼節點,用後繼覆蓋root,然後在右子樹中刪除後繼節點
node* next = findMin(root->rchild);
root->data = next->data;
deleteNode(root->rchild, next->data);
}
}
else if (root->data > x)
deleteNode(root->lchild, x); // 往左子樹中查找,刪除
else
deleteNode(root->rchild, x); // 往右子樹中查找,刪除
}
int main()
{
return 0;
}