代码改变世界

二叉搜索树的查找与删除

2015-03-29 23:38  李涛的技术博客  阅读(284)  评论(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;
}