Home > Enterprise >  Finding the intersection of two binary search trees
Finding the intersection of two binary search trees

Time:10-07

I am building and returning a new binary search tree constructed of the intersection of two other binary search trees. I have available to me a find function which I am using to check if any values of the first tree are found in the second tree and if they are I insert them into a new tree. My issue is that the new tree "res" does not update upon recursion. So if I test it with 8, 4, 10 for tree1 and tree2 is 8, 6, 4, 13 my new tree only contains 8 and not 8 and 4. Grateful for any feedback!

BinSearchTree *BinSearchTree::intersectWith(TreeNode *root1, TreeNode *root2) {
BinSearchTree *res = new BinSearchTree();

//traverse one tree and use find to traverse the second tree
if(local_find(root2, root1->value()) && !local_find(res->root, root1->value()))
    res->insert(root1->value());
if(root1->leftSubtree() != nullptr)
    intersectWith(root1->leftSubtree(), root2);
if(root1->rightSubtree() != nullptr)
    intersectWith(root1->rightSubtree(), root2);
return res;

}

CodePudding user response:

You are overwriting res every time you call intersectWith() by calling 'new BinSearchTree()'.

To fix this, create res outside of interSectWith() and then pass it in as a third parameter. (You could then also consider making intersectWith() return void, as a return value is no longer needed.)

  • Related