二叉排序树

二叉排序树的性质:
在这里插入图片描述
二叉排序树的插入操作:
在这里插入图片描述
③的左右孩子均为空,且由于此树的性质,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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值