二叉排序的创建,删除,遍历,查找

#include <iostream>
using namespace std;

typedef struct Node{
    int val;
    Node *left;
    Node *right;
}Node,*PNode;

void insert(PNode &p,int key){
    if(p == NULL){
        p = new Node;
        p->val = key;
        p->left = NULL;
        p->right = NULL;
        return;
    }
    if(key == p->val){
        cout << "insert error is equal" << endl;
    }
    if(key > p->val){
        insert(p->right,key);
    }else{
        insert(p->left,key);
    }
}
PNode deleteNode(PNode p){
    if(p->left != NULL){
        PNode r = p->left;
        while(r->right != NULL){
            r = r->right;
        }
        r->right = p->right;
        r = p->left;
        delete p;
        return r;
    }else{
        PNode r = p->right;
        delete p;
        return r;
    }
}
void delete_order(PNode &p,int key){
    if(p == NULL){
        return ;
    }
    if(p->val == key){
        p = deleteNode(p);
    }else{
        if(p->val > key){
            delete_order(p->left,key);
        }else{
            delete_order(p->right,key);
        }
    }
}
void pre_order(PNode p){
    if(p == NULL){
        return ;
    }
    cout << p->val << endl;
    pre_order(p->left);
    pre_order(p->right);
}
void in_order(PNode p){
    if(p == NULL){
        return ;
    }
    in_order(p->left);
    cout << p->val << endl;
    in_order(p->right);
}
void post_order(PNode p){
    if(p == NULL){
        return ;
    }
    post_order(p->left);
    post_order(p->right);
    cout << p->val << endl;
}
bool find(PNode p,int key){
    if(p == NULL){
        return false;
    }
    if(p->val == key){
        return true;
    }
    if(p->val > key){
        find(p->left,key);
    }else{
        find(p->right,key);
    }
}
void freeNode(PNode p){
    if(p == NULL){
        return ;
    }
    if(p->left != NULL){
        freeNode(p->left);
    }
    if(p->right != NULL){
        freeNode(p->right);
    }
    delete p;
}
int main()
{
    PNode p = NULL;
    int a[] = {10,8,12,7,9,11};
    for(int i=0;i<sizeof(a)/sizeof(int);i++){
        //cout << a[i] << endl;
        insert(p,a[i]);
    }
    //delete_order(p,11);
    //pre(p);
    in_order(p);
    //post_order(p);
    if(find(p,100)){
        cout << "find " << endl;
    }else{
        cout << "not find" << endl;
    }
    freeNode(p);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值