二叉搜索树
定义
优点
代码实现
#include<iostream>
using namespace std;
typedef int Elemtype;
typedef struct node
{
Elemtype data;
struct node* left, * right;
}BinNode,*BinTree;
void CreateBinSerchTree(BinTree& node, Elemtype arr[], int n);
void Create_Bin_Serch_Tree(BinTree& node, Elemtype arr[], int n);
void Insert(BinTree& node, Elemtype key);
void Serch(BinTree root, Elemtype key, int& height);
BinTree DelNode(BinTree root, Elemtype key);
void InOrder(BinTree root);
void CreateBinSerchTree(BinTree& node, Elemtype arr[], int n)
{
node = new BinNode;
node->data = arr[0];
node->left = node->right = NULL;
int flag = 2;
for (int i = 1; i < n; i++)
{
flag = 2;
BinTree p = node, q = node, r = new BinNode;
r->data = arr[i];
r->left = r->right = NULL;
while (p != NULL)
{
q = p;
if (p->data < arr[i])
{
p = p->right;
flag = 1;
}
else if (p->data > arr[i])
{
p = p->left;
flag = 0;
}
}
if (flag)
q->right = r;
else
q->left = r;
}
}
void Insert(BinTree& node, Elemtype key)
{
if (node == NULL)
{
node = new BinNode;
node->data = key;
node->left = node->right = NULL;
}
else if (node->data > key)
Insert(node->left, key);
else
Insert(node->right, key);
}
void Create_Bin_Serch_Tree(BinTree& node, Elemtype arr[], int n)
{
node = new BinNode;
node->data = arr[0];
node->left = node->right = NULL;
for (int i = 1; i < n; i++)
{
Insert(node, arr[i]);
}
}
void Serch(BinTree root, Elemtype key, int& height)
{
if (root == NULL)
{
height = -1;
return;
}
if (root->data == key)
{
height++;
return;
}
else if (root->data > key)
Serch(root->left, key, height);
else
Serch(root->right, key, height);
}
BinTree DelNode(BinTree root, Elemtype key)
{
if (root == NULL)
return root;
if (key < root->data)
{
root->left = DelNode(root->left, key);
}
else if (key > root->data)
{
root->right = DelNode(root->right, key);
}
else
{
if (root->left == NULL)
{
BinTree temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL)
{
BinTree temp = root->left;
delete root;
return temp;
}
BinTree p = root->right, temp = NULL;
while (p->left != NULL)
{
p = p->left;
}
temp = p;
root->data = temp->data;
root->right = DelNode(root->right, temp->data);
}
return root;
}
void InOrder(BinTree root)
{
if (root == NULL)
return;
InOrder(root->left);
cout << root->data << " ";
InOrder(root->right);
}