BST的基本代码实现(详细注释)
用的都是非常朴素的方法,欢迎交流讨论
#include<iostream>
#include<queue>
using namespace std;
typedef struct Bnode {
Bnode*left, *right;
int data;
}BSTnode, *BSTree;
void insert(BSTree &root,int val)//改变内容需用指针的引用
{
if (!root)
{
root = new BSTnode;
root->left = NULL;
root->right = NULL;
root->data = val;
}
else
{
if (val > root->data)//大于当前节点值,放在右边,反之左边
{
insert(root->right, val);
}
else
insert(root->left, val);
}
}
void input(BSTree &root,int n)//初始化BST树
{
cout << "please cin the number\n";
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
insert(root, x);
}
}
BSTree find(int key, BSTree root)
{
if (root)
{
if (root->data == key)
return root;
if (root->data < key)
return find(key, root->right);
if (root->data > key)
return find(key, root->left);
}
else
return NULL;
}
void layer_tra(BSTree root)//层次遍历
{
if (!root) return;
queue<BSTree>q1;
q1.push(root);
while (!q1.empty())
{
cout << q1.front()->data << ' ';
if(q1.front()->left)
q1.push(q1.front()->left);
if (q1.front()->right)
q1.push(q1.front()->right);
q1.pop();
}
cout << endl;
}
void delete_node(BSTree &root, int val)
{
if (root)
{
//首先寻找到该节点以及父节点,用isleft来判断左右子树的关系
BSTnode*pre = NULL;
BSTnode*now = root;
bool isleft;
while (now)
{
if (now->data < val)
{
pre = now;
now = now->right;
isleft = 0;
}
else if(now->data>val)
{
pre = now;
now = now->left;
isleft = 1;
}
else
{
break;
}
}
//接下来为删除部分
if (!now)//如果未找到
{
cout << "cant find\n";
return;
}
else
{
if (now == root)//如果为根节点
{
BSTnode*tmp = root->right;//用tmp来存放后继
if (!tmp)//如果根节点无右子树,直接删除根节点,改变root指向
{
tmp = root;
root = root->left;
delete tmp;
return;
}
BSTnode*parent = NULL;
while (tmp->left)
{
parent = tmp;
tmp = tmp->left;
}
if (!parent)//如果tmp无左子树
{
now->data = tmp->data;
now->right = tmp->right;
delete tmp;
return;
}
now->data = tmp->data;
parent->left = NULL;
delete tmp;
return;
}
//接下来为非根节点
if (!now->left && !now->right)//叶子节点直接删除
{
delete now;
return;
}
if (!now->left&&now->right)//如果当前节点只有右子树
{
if (isleft)//如果当前节点为父节点的左子树
{
pre->left = now->right;
delete now;
return;
}
else
{
pre->right = now->right;
delete now;
return;
}
}
if (now->left && !now->right)//只有左子树
{
if (isleft)
{
pre->left = now->left;
delete now;
return;
}
else
{
pre->right = now->left;
delete now;
return;
}
}
if (now->left&&now->right)//度为2
{
BSTnode*tmp = now->right;//用tmp来存放后继
BSTnode*parent = NULL;
while (tmp->left)
{
parent = tmp;
tmp = tmp->left;
}
if (!parent)//如果tmp无左子树,则直接用tmp与now替换,并删除tmp
{
now->data = tmp->data;
now->right = tmp->right;
delete tmp;
return;
}
now->data = tmp->data;
parent->left = NULL;
delete tmp;
return;
}
}
}
}
void inorder(BSTree root)
{
if (root)
{
inorder(root->left);
cout << root->data << ' ';
inorder(root->right);
}
}
int main()
{
BSTree root=NULL;
BSTree tmp = NULL;
int n;
cout << "please inupt n numbers:\n";
cin >> n;
input(root, n);
}