📅  最后修改于: 2020-10-15 01:01:12             🧑  作者: Mango
上图中显示了二进制搜索树。作为对BST施加的约束,我们可以看到根节点30在其左子树中不包含任何大于或等于30的值,并且在其右子树中也不包含任何小于30的值。 -树。
43,10,79,90,12,54,11,11,50
下图显示了使用给定元素创建BST的过程。
在二进制搜索树上可以执行许多操作。
SN | Operation | Description |
---|---|---|
1 | Searching in BST | Finding the location of some specific element in a binary search tree. |
2 | Insertion in BST | Adding a new element to the binary search tree at the appropriate location so that the property of BST do not violate. |
3 | Deletion in BST | Deleting some specific node from a binary search tree. However, there can be various cases in deletion depending upon the number of children, the node have. |
#include
#include
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
};
Node* create(int item)
{
Node* node = new Node;
node->data = item;
node->left = node->right = NULL;
return node;
}
void inorder(Node *root)
{
if (root == NULL)
return;
inorder(root->left);
cout<< root->data << " ";
inorder(root->right);
}
Node* findMinimum(Node* cur)
{
while(cur->left != NULL) {
cur = cur->left;
}
return cur;
}
Node* insertion(Node* root, int item)
{
if (root == NULL)
return create(item);
if (item < root->data)
root->left = insertion(root->left, item);
else
root->right = insertion(root->right, item);
return root;
}
void search(Node* &cur, int item, Node* &parent)
{
while (cur != NULL && cur->data != item)
{
parent = cur;
if (item < cur->data)
cur = cur->left;
else
cur = cur->right;
}
}
void deletion(Node*& root, int item)
{
Node* parent = NULL;
Node* cur = root;
search(cur, item, parent);
if (cur == NULL)
return;
if (cur->left == NULL && cur->right == NULL)
{
if (cur != root)
{
if (parent->left == cur)
parent->left = NULL;
else
parent->right = NULL;
}
else
root = NULL;
free(cur);
}
else if (cur->left && cur->right)
{
Node* succ = findMinimum(cur- >right);
int val = succ->data;
deletion(root, succ->data);
cur->data = val;
}
else
{
Node* child = (cur->left)? Cur- >left: cur->right;
if (cur != root)
{
if (cur == parent->left)
parent->left = child;
else
parent->right = child;
}
else
root = child;
free(cur);
}
}
int main()
{
Node* root = NULL;
int keys[8];
for(int i=0;i<8;i++)
{
cout << "Enter value to be inserted";
cin>>keys[i];
root = insertion(root, keys[i]);
}
inorder(root);
cout<<"\n";
deletion(root, 10);
inorder(root);
return 0;
}
输出:
Enter value to be inserted? 10
Enter value to be inserted? 20
Enter value to be inserted? 30
Enter value to be inserted? 40
Enter value to be inserted? 5
Enter value to be inserted? 25
Enter value to be inserted? 15
Enter value to be inserted? 5
5 5 10 15 20 25 30 40
5 5 15 20 25 30 40