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 mean delete all the nodes present in B from A. Note: B is not necessarily a subtree of A.
eg:
A:
50 / \ 10 75 / / \ 1 60 90
B:
10 / \ 1 75
Resulting tree should be:
50 \ 60 \ 90
Two approaches came to my mind:
A1:
node* deleteTree(node* A, node* B) ;
Take the root of tree B. Delete this node from tree A(by normal BSt deletion method). Next divide the problem into two parts - for the left subtree of B and the right subtree of B. For each of the subtree, recurse. For the left subtree, the node which occupied the node which was deleted should serve as the root for tree A. For the right subtree, the inorder successor of the deleted node should server as the root for tree A.
A2: The other approach is a little weird. I find the inorder and preorder traversal of tree A. Find and delete all the nodes in tree B using binary search along with recursion(we dont modify the preorder). Finally recostruct our bst from the inorder(remaining) and the preorder(unchanged).
Prob A: Find an efficient way for BST.
Prob B: Find an efficient way for any Binary tree(not just BST).