C++写一个BST

C++写一个BST,第1张

C++写一个BST BST

手写一个二叉搜索树

#include 
using namespace std;

struct node
{
    int value;
    node *left;
    node *right;
};

node* insert(node *n,int value)
{
    if(n == NULL)
    {
        node *n = new node;
        n->left = NULL;
        n->right = NULL;
        n->value = value;
        return n;
    }
    
    if(value < n->value)
    {
        n->left = insert(n->left, value);
        return n;
    }
    else if(value > n->value)
    {
        n->right = insert(n->right, value);
        return n;
    }
    
}

node *remove(node *n, int val)
{
    if(n->value == val)
    {
        if(n->right == NULL)
        {
            node *ptr = n->left;
            delete n;
            return ptr;
        }
        else
        {
            node *ptr = n->right;
            while(ptr->left)
            {
                ptr = ptr->left;
            }
            n->value = ptr->value;
            n->right = remove(n->right, ptr->value);
            return n;
        }
    }

    if(n->left != NULL)
        n->left = remove(n->left, val);
    if(n->right != NULL)
        n->right = remove(n->right, val);
    return n;
}

int main()
{
    node *root = NULL;

    root = insert(root,10);
    root = insert(root,5);
    root = insert(root,2);
    root = insert(root,20);

    remove(root,10);
    cout << root->left->value;
    
    system("pause");
    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5714350.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存