二叉树的代码

#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;
}

 

posted @ 2020-04-25 11:30  月光下の魔术师  阅读(6)  评论(0)    收藏  举报