2.排序二叉树
2.1 创建一个排序二叉树
- 1.对于一个排序二叉树,我们知道其所有左子树上的元素的值都比根节点的值小,其所有右子树上的元素的值都比根节点大,因此很容易就可以构建一颗排序二叉树;
- 2.我们使用一个函数来对其中的节点进行添加,我们需要将左子树上的所有节点的值都小于根节点的值,将右子树上的值都大于根节点的值,因此我们需要有一个节点来存储添加的节点的值;
typedef struct tree
{
int n_value;
struct tree* p_left;
struct tree* p_right;
}BinaryTree;
void AddNode(BinaryTree** pp_tree, int num)
{
BinaryTree* p_node = NULL;
BinaryTree* p_temp = NULL;
p_temp = (BinaryTree*)malloc(sizeof(BinaryTree));
p_temp->n_value = num;
p_temp->p_left = NULL;
p_temp->p_right = NULL;
if(*pp_tree == NULL)
{
*pp_tree = p_temp;
return;
}
p_node = *pp_tree;
while(p_node)
{
if(num < p_node->n_value)
{
if(p_node->p_left == NULL)
{
p_node->p_left = p_temp;
return;
}
p_node = p_node->p_left;
}
else if(num > p_node->n_value)
{
if(p_node->p_right == NULL)
{
p_node->p_right = p_temp;
return;
}
p_node = p_node->p_right;
}
else
{
free(p_temp);
p_temp = 0;
return;
}
}
}
BinaryTree* CreateBST(int arr[], int len)
{
int i;
BinaryTree* p_tree = NULL;
if(arr == NULL || len <= 0)return NULL;
for(i=0; i<len; i++)
{
AddNode(&p_tree, arr[i]);
}
return p_tree;
}
- 3.我们可以通过一个中序遍历来检查我们创建的排序二叉树是否能够正常添加节点,以及节点的位置是否正确;
2.2 删除排序二叉树中的节点
- 1.排序二叉树中的节点很好找到,因为它是有序的;但是当我们想要删除一个节点时,我们就需要考虑该如何进行删除,删除之后应该如何将剩下的节点放置之后结果仍是一颗排序二叉树;
- 2.我们有两种方法来进行:1)在被删除节点的左子树中找其中最靠右的节点;2)在被删除节点的右子树中找其中最靠左的节点;
- 3.在被删除节点的左子树中找其中最靠右的节点:我们将左子树中最大的值作为被删除节点的替换节点,这样原节点的右子树不需要进行改动,而其左子树只需找个合适的即可;
void FindDel(BinaryTree* p_tree, int num, BinaryTree** pp_del, BinaryTree** pp_father)
{
while(p_tree)
{
if(num = p_tree->n_value)
{
*pp_del = p_tree;
return;
}
else if(num < p_tree->n_value)
{
*pp_father = p_tree;
p_tree = p_tree->p_left;
}
else
{
*pp_father = p_tree;
p_tree = p_tree->p_right;
}
}
*pp_father = NULL;
}
void DelNode(BinaryTree** pp_tree, int num)
{
BinaryTree* p_del = NULL;
BinaryTree* p_father = NULL;
BinaryTree* p_flag = NULL;
if(*pp_tree == NULL)return;
FindDel(*pp_tree, num, &p_del, &p_father);
if(p_del == NULL)return;
if(p_del->p_left != NULL && p_del->p_right != NULL)
{
p_flag = p_del;
p_father = p_del;
p_del = p_del->p_right;
while (p_del->p_left)
{
p_father = p_del;
p_del = p_del->p_left;
}
p_flag->n_value = p_del->n_value;
}
if(p_father == NULL)
{
*pp_tree = p_del->p_left?p_del->p_left:p_del->p_right;
free(p_del);
p_del = 0;
return;
}
if(p_del == p_father->p_left)
{
p_father->p_left = p_del->p_left?p_del->p_left:p_del->p_right;
}
else
{
p_father->p_right = p_del->p_left?p_del->p_left:p_del->p_right;
}
free(p_del);
p_del = 0;
return;
}