码迷,mamicode.com
首页 > 其他好文 > 详细

二叉搜索树的查找与删除

时间:2015-03-30 01:31:36      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

在二叉搜索树中查找一个数,如果存在,则从树中删除。

struct Node
{
    Node* left;
    Node* right;
    int data;
};

void findAndDel(Node*& head, int k)
{
    if (!head)
        return;
    Node* node = head;
    Node* vnode = new Node;
    vnode->left = vnode->right = head;
    Node* pnode = vnode;
    // find node
    while (node)
    {
        if (node->data > k)
        {
            if (node->left == NULL)
                return;
            else
            {
                pnode = node;
                node = node ->left;
            }
        }
        else if (node->data < k)
        {
            if (node->right == NULL)
                return;
            else
            {
                pnode = node;
                node = node->left;
            }
        }
        else
            break;
    }
    // found
    if (node->left == NULL)
    {
        if (pnode->right == node)
            pnode->right = node->right;
        else
            pnode->left = node->right;
        delete node;
    }
    else if (node->right == NULL)
    {
        if (pnode->right == node)
            pnode->right = node->left;
        else
            pnode->left = node->left;
        delete node;
    }
    else
    {
        Node* leftBiggest = node->left;
        Node* leftBiggestP = node;
        while (leftBiggest->right != NULL)
        {
            leftBiggestP = leftBiggest;
            leftBiggest = leftBiggest->right;
        }
        node->data = leftBiggest->data;
        if (leftBiggestP->left == leftBiggest)
            leftBiggestP->left = leftBiggest->left;
        else
            leftBiggestP->right = leftBiggest->left;
        delete leftBiggest;
    }
    head = vnode->right;
    delete vnode;
}

 

二叉搜索树的查找与删除

标签:

原文地址:http://www.cnblogs.com/litao-tech/p/4376742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!