二叉排序树的性质:
二叉排序树的插入操作:
③的左右孩子均为空,且由于此树的性质,10置为③的右孩子,结束。
二叉排序树的删除:
解决思路:
1.直接删除
2.如图:
3.如图:
中序遍历为:17-18-19-20-28-29-30-32
LeetCode:
代码实现:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node{
int key;
struct Node *lchild, *rchild;
}Node;
Node *get_node(int key){
Node * p = (Node *)malloc(sizeof(Node));
p->key = key;
p->lchild = p->rchild = NULL;
return p;
}
Node *insert(Node *root, int key){
if(root == NULL) return get_node(key);
if(root->key == key) return root;
if(key < root->key){
root->lchild = insert(root->lchild, key);
}else{
root->rchild = insert(root->rchild, key);
}
return root;
}
Node *pre(Node *root){
Node *temp = root->lchild;
while(temp->rchild) temp = temp->rchild;
return temp;
}
Node *delete_node(Node *root, int key){
if(root == NULL) return root;
if(key < root->key) root->lchild = delete_node(root->lchild, key);
else if(key > root->key) root->rchild - delete_node(root->rchild, key);
else{
if(root->lchild == NULL || root->rchild == NULL){
Node *temp = root->lchild ? root->lchild : root->rchild;
free(root);
return temp;
}else{
Node *temp = pre(root);
root->key = temp->key;
root->lchild = delete_node(root->lchild, temp->key);
}
}
return root;
}
void __in_order(Node *root){
if(root == NULL) return;
__in_order(root->lchild);
printf("%d ", root->key);
__in_order(root->rchild);
return;
}
void in_order(Node *root){
printf("in_order output : ");
__in_order(root);
printf("\n");
return;
}
void clear(Node *root){
if(root == NULL) return;
clear(root->lchild);
clear(root->rchild);
free(root);
return;
}
int main(){
int op, val;
Node *root = NULL;
while(~scanf("%d%d", &op, &val)){
switch(op){
case 1: root = insert(root, val); break;
case 2: root = delete_node(root, val); break;
}
in_order(root);
}
clear(root);
return 0;
}
实现结果:
1 3
in_order output : 3
1 2
in_order output : 2 3
1 5
in_order output : 2 3 5
1 15
in_order output : 2 3 5 15
1 -2
in_order output : -2 2 3 5 15
1 20
in_order output : -2 2 3 5 15 20
2 3
in_order output : -2 2 5 15 20