deletion in a binary search tree

后端 未结 2 499
故里飘歌
故里飘歌 2021-01-02 17:37

I have been given two binary search trees. For example, A and B. Next, I was asked to delete the tree B from the tree A.

By deletion, I

相关标签:
2条回答
  • 2021-01-02 18:07

    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).

    0 讨论(0)
  • 2021-01-02 18:29

    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.

    0 讨论(0)
提交回复
热议问题