Intersection of two trees

QUESTION 
Write a function that constructs a binary tree resulting from the structural intersection of two binary trees, i.e. only the nodes that are present in both trees are created in the third one, but the values of the keys are not important, and can differ. For example, if the root nodes of the two trees both have a left child then a left child is added to the root of the resulting tree, otherwise it is set to NULL, and so on.  When a new node is created in the result tree for two corresponding nodes of the input trees, the minimum value key is copied to the newly created node. An example is given below:


The function should take two root node pointers (of tree A and tree B) as input parameters, and return the root pointer to the newly contstructed tree (tree C).  If you use any helper functions then implement them also.  Also, a node DOES NOT have a pointer to the parent node and there is no function to return the depth of the tree.

SOLUTION

node *intersect(node *A,node*B)
{
            node *n=nullptr;
            if (A&&B)
            {
                        n=new node(min(A->key,B->key));
                        construct(A,B,n);
}
}

void construct(node *A,node *B, node*C)
{
            if (A->left && B->left)
            {
                        int key = min(A->left->key,B->left->key);
                        C->left = new node(key);
                        construct(A->left,B->left,C->left);
}
            if (A->right && B-> right)
            {
                        int key = min(A-> right ->key,B-> right ->key);
                        C-> right = new node(key);
                        construct(A-> right,B-> right,C-> right);
}

}

Comments

Popular Posts