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
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).
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.
Use hash table for one tree and traverse another. You will get O(N) for both time and space complexity.