deletion in a binary search tree

Deadly 提交于 2019-11-30 14:04:11

Problem A

I assume the two trees are balanced.

void deleteTree(node* A, node* B)
{
    if(A == NULL || B == NULL)
        return;

    if(A->data == B->data)
    {
        deleteTree(A->left, B->left);
        deleteTree(A->right, B->right);
        removeNode(A); // Normal BST remove
    }
    else if(A->data > B->data)
    {
        Node* right = B->right;
        B->right = NULL;
        deleteTree(A->left, B);
        deleteTree(A, right);
    }
    else // (A->data < B->data)
    {
        Node* left = B->left;
        B->left = NULL;
        deleteTree(A->right, B);
        deleteTree(A, left);
    }
}

Time complexity:

T(N) = 2 * T(N / 2) + O(1)

So the overall complexity is O(N) according to master theorem. The space complexity is O(1). One drawback is I destructed B.

PS: I don't have a BST implementation at hand so I can't test the code for you. But I think the idea is correct.

Problem B

Use hash table for one tree and traverse another. You will get O(N) for both time and space complexity.

The way I see it, why don't you do an inorder traversal of b. Then, until the array is not empty, do a regular delete from a for the value of the array index. Traversal is O(n) and deletion for each index will be O(logn). Totally, this operation will be O(nlogn).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!