首页 > 编程语言 > 详细

二叉排序树

时间:2020-07-28 22:01:06      阅读:53      评论:0      收藏:0      [点我收藏+]
#include<iostream>
#include<queue>
using namespace std;

struct BSTNode{
    int data;
    BSTNode *left,*right;
    BSTNode(int x,BSTNode* L=NULL,BSTNode* R=NULL){
        data=x;
        left=L;
        right=R;
    }
};
class BST{
public:
    BSTNode* root=NULL;
public:
    BST(int arr[],int n){
        for(int i=0;i<n;i++){
            Insert(arr[i]);
        }
    }
    BSTNode* Search(int x){
        Search(x,root);
    }
    BSTNode* Search(int x,BSTNode* ptr){
        if(ptr==NULL){
            return NULL;
        }else if(x<ptr->data){
            return Search(x,ptr->left);
        }else if(x>ptr->data){
            return Search(x,ptr->right);
        }else{
            return ptr;
        }
    }
    bool Insert(int x){
        Insert(x,root);
    }
    bool Insert(int x,BSTNode* &ptr){
        if(ptr==NULL){
            ptr=new BSTNode(x);
            return true;
        }else if(x<ptr->data){
            Insert(x,ptr->left);
        }else if(x>ptr->data){
            Insert(x,ptr->right);
        }else{
            return false;
        }
    }
    bool Remove(int x){
        Remove(x,root);
    }
    bool Remove(int x,BSTNode* &ptr){
        BSTNode* temp;
        if(ptr!=NULL){
            if(x<ptr->data){
                Remove(x,ptr->left);
            }else if(x>ptr->data){
                Remove(x,ptr->right);
            }else if(ptr->left!=NULL&&ptr->right!=NULL){
                temp=ptr->right;
                while(temp->left!=NULL){
                    temp=temp->left;
                }
                ptr->data=temp->data;
                Remove(ptr->data,ptr->right);
            }else{
                temp=ptr;
                if(ptr->left==NULL){
                    ptr=ptr->right;
                }else{
                    ptr=ptr->left;
                }
                delete temp;
                return true;
            }
        }
        return false;
    }
    void LevelTraversal(){
        if(root!=NULL){
            queue<BSTNode*> Q;
            BSTNode* p=root;
            Q.push(p);
            while(!Q.empty()){
                p=Q.front();
                cout<<p->data<<" ";
                Q.pop();
                if(p->left!=NULL){
                    Q.push(p->left);
                }
                if(p->right!=NULL){
                    Q.push(p->right);
                }
            }
        }
    }
};
int main(){
    int arr[]={53,17,78,9,45,65,87,23,81,94};
    BST bst(arr,sizeof(arr)/sizeof(int));
    bst.LevelTraversal();
    cout<<endl;
    bst.Remove(94);
    bst.LevelTraversal();
    cout<<endl;
    bst.Insert(100);
    bst.LevelTraversal();
    cout<<endl;
    return 0;
}

 

二叉排序树

原文:https://www.cnblogs.com/zzyf/p/13392570.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!