First, the definition
Binary sort tree (Binary Sort Tree) or an empty tree, or to meet the following properties of a non-null binary tree T:
- If the left subtree of T is not empty, then the left subtree of all the nodes is smaller than the value of the root of T;
- If the right subtree of T is not empty, all the right subtree root node is greater than the value of T;
- T left subtree and right subtree are binary sort tree.
Second, find keywords
(1) algorithm ideas
(2) achieve
typeof struct BTNode
{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
BTNode * BSTsearch(BTNode *bt,int key)
{
if(bt==NULL)
return NULL;
else
{
if(bt->key==key)
return bt; // 等于根结点中的关键字,查找成功,返回关键字所在的结点指针
else if(key<bt->key)
return BSTsearch(bt->lchild,key);
else
return BSTsearch(bt->rchild,key);
}
}
Third, insert keywords
(1) algorithm ideas
(2) achieve
typeof struct BTNode
{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
int BSTinsert(BTNode *&bt,int key) // 因为指针bt要改变,所以要用引用型指针
{
if(bt==NULL)
{
bt=(BTNode*)malloc(sizeof(BTNode)); // 创建新结点
bt->lchild=bt->lchild=NULL;
bt->key=key;
return 1; // 插入成功,返回1
}
else
{
if(bt->key==key)
return -1; // 等于根结点中的关键字,插入失败,返回-1
else if(key<bt->key)
return BSTsearch(bt->lchild,key);
else
return BSTsearch(bt->rchild,key);
}
}
Create four binary sort tree
(1) algorithm ideas
(2) achieve
void CreateBST(BTNode *&bt,int key[],int n)
{
int i;
bt=NULL; // 将树清空
for(i=0;i<n;i++)
BSTinsert(bt,key[i]);
}
V. delete keywords
(1) algorithm ideas
When you delete a keyword in the binary sort tree, not to the node where the key is the root of the subtree are deleted, but only delete a node, and retention characteristics binary sort tree. Procedure to remove the node p is divided into the following three cases
1. p is a leaf node the node (if the node p 21)
- Deleted directly
2. p junction only, without the right subtree of the left subtree, and no or only a left subtree right subtree. (If p is the node 56)
- At this time, only you need to delete p, then p subtree pointer connected directly connected to the original p f to its parent node.
3. p nodes have both left subtree right subtree. (If p junction 64, then node 56 r)
- The root node in the left subtree pointer p has a right to go right, until a node went right subtree rightmost
- It is then replaced by p r keywords in the keyword.
- Final judgment, if r is a leaf node, then according to (1) Method remove r; r if non-leaf node, then according to (2) Method remove r.