Given a binary tree, find the sum of the product of each node and its mirror image (The mirror of a node is a node which exists at the mirror position of the node in opposite subtree at the root), not taking into account a pair more than once. The root node is the mirror image of itself. The answer may be very large, compute the answer modulo 10 9 + 7.
The mirror of a node in a binary tree is the node located at the same position but in the opposite subtree when considering the root as the center of mirroring. For a given node, its mirror can be identified by traversing the tree symmetrically.
We need to calculate the sum of the product of each node with its mirror image. The root node is its own mirror, so its contribution to the sum is square of root's value . For other nodes, their product with their mirror should be included only once.
Use a recursive function to simultaneously traverse the left and right subtrees. For each pair of nodes (one from the left subtree and one from the right subtree), compute the product and add it to the sum. Ensure that each pair is only counted once.
Step-by-step algorithm:
Create a helper function that takes two nodes as parameters and computes the sum of products of these nodes and their children. This function will be called initially with the left and right children of the root. We recursively call this function on left child of left tree and right child of right tree & also on right child of left tree and left child of right tree.
If either of the nodes in the pair is null, return 0 as the product involving a null node is 0.
Calculate the product of the current pair of nodes and add it to the recursive results of their children.
In the main function, initialize the sum with the square of the root value. Use the helper function to add the sum of products for the left and right subtrees.
Given that the result can be very large, compute the answer modulo 10 9 +7 and return it.
Following is the implementation of above approach:
C++
#include<iostream>usingnamespacestd;// Define the structure for NodestructNode{longlongdata;Node*left,*right;// Constructor to initialize data and left/right// pointersNode(longlongval):data(val),left(nullptr),right(nullptr){}};voidsolve(Node*leftTree,Node*rightTree,longlongint&sum){if(!leftTree||!rightTree)return;sum=sum+(leftTree->data*rightTree->data);solve(leftTree->left,rightTree->right,sum);solve(leftTree->right,rightTree->left,sum);}intmod=1e9+7;// Function to perform image multiplicationlonglongimgMultiply(Node*root){// Base caseif(!root)return0;// Initialize sum with square of root node's datalonglongintsum=root->data*root->data;// Recursively calculate sum of products of// corresponding nodessolve(root->left,root->right,sum);// Return the result modulo modreturnsum%mod;}intmain(){// Example usage// Create a sample binary treeNode*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);/* The binary tree created looks like this: 1 / \ 2 3 / \ / \ 4 5 6 7 */// Call the imgMultiply function and print the resultcout<<"Result: "<<imgMultiply(root)<<endl;// Clean up allocated memorydeleteroot->right->right;deleteroot->right->left;deleteroot->left->right;deleteroot->left->left;deleteroot->right;deleteroot->left;deleteroot;return0;}
Java
importjava.util.Objects;// Define the structure for NodeclassNode{longdata;Nodeleft,right;// Constructor to initialize data and left/right// pointersNode(longval){data=val;left=null;right=null;}}publicclassMain{staticintmod=1000000007;// Recursive function to calculate the sum of products// of corresponding nodesstaticvoidsolve(NodeleftTree,NoderightTree,long[]sum){if(Objects.isNull(leftTree)||Objects.isNull(rightTree))return;sum[0]=(sum[0]+(leftTree.data*rightTree.data))%mod;solve(leftTree.left,rightTree.right,sum);solve(leftTree.right,rightTree.left,sum);}// Function to perform image multiplicationstaticlongimgMultiply(Noderoot){// Base caseif(Objects.isNull(root))return0;// Initialize sum with square of root node's datalong[]sum={root.data*root.data};// Recursively calculate sum of products of// corresponding nodessolve(root.left,root.right,sum);// Return the result modulo modreturnsum[0];}publicstaticvoidmain(String[]args){// Example usage// Create a sample binary treeNoderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);/* The binary tree created looks like this: 1 / \ 2 3 / \ / \ 4 5 6 7 */// Call the imgMultiply function and print the// resultSystem.out.println("Result: "+imgMultiply(root));}}
Python
# Define the structure for NodeclassNode:def__init__(self,val:int)->None:self.data:int=valself.left:Optional[Node]=Noneself.right:Optional[Node]=Nonemod=10**9+7# Recursive function to calculate the sum of products of corresponding nodesdefsolve(leftTree,rightTree,sum)->None:ifnotleftTreeornotrightTree:returnsum[0]=sum[0]+(leftTree.data*rightTree.data)solve(leftTree.left,rightTree.right,sum)solve(leftTree.right,rightTree.left,sum)# Function to perform image multiplicationdefimgMultiply(root)->int:# Base caseifnotroot:return0# Initialize sum with square of root node's datasum=[root.data*root.data]# Recursively calculate sum of products of corresponding nodessolve(root.left,root.right,sum)# Return the result modulo modreturnsum[0]%mod# Example usage# Create a sample binary treeroot=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)# Call the imgMultiply function and print the resultprint("Result:",imgMultiply(root))# Clean up allocated memorydelroot.right.rightdelroot.right.leftdelroot.left.rightdelroot.left.leftdelroot.rightdelroot.leftdelroot
Output
Result: 65
Time Complexity: O(n), as we are traversing the whole tree to calculate product of the mirror image of the nodes. Auxiliary Space: O(h), as we are using recursion stack space.