二叉树的代码

#include <bits/stdc++.h>
using namespace std;
int const N = 1000 + 10;
typedef struct BST{
    struct BST *left,*right;
    int val;
}*Node;
Node insert(Node root,int key){
    if(root == NULL){
        root = new BST();
        root->left = root->right = NULL;
        root->val = key;
    }else{
        if(key < root->val)
            root->left = insert(root->left,key);
        else
            root->right = insert(root->right,key);
    }
    return root;
}
Node search(Node root,int key){
    if(!root || root->val == key)   return root;
    else if(key < root->val)    return search(root->left,key);
    else if(key > root->val)    return search(root->right,key);
}
Node Search_min(Node root){
    if(root->left == NULL)  return root;
    else    return Search_min(root->left);
}
Node Delete(Node root,int key){
    if(!root)   return root;
    if(root->val == key){
        if(root->left && root->right){
            Node tmp = Search_min(root->right); //寻找后继结点
            swap(root->val,tmp->val);
            root->right = Delete(root->right,tmp->val);
        }else{
            if(!root->left)  root = root->right;
            else root = root->left;
        }

    }
    else if(key < root->val)
        root->left = Delete(root->left,key);
    else if(key > root->val)
        root->right = Delete(root->right,key);
    return root;
}
void order(Node root){
    if(root == NULL)    return;
    order(root->left);
    printf("%d\n",root->val);
    order(root->right);
}
int main(){
    int n = 10;
    Node root = NULL;
    int test[12]={12,49,5,12,56,32,45,67,98,15};
    for(int i=0;i<n;i++){
        root = insert(root,test[i]);
    }
    Delete(root,5);
    order(root);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值