Merge Two Binary Trees by doing Node Sum ( Recursive and Iterative ) | Helper class that allocates a new node with the given data and None left and right pointers . ; Given a binary tree , prits nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Function to merge given two binary trees ; Driver code ; Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 ; Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def inorder ( node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE inorder ( node . right ) NEW_LINE DEDENT def MergeTrees ( t1 , t2 ) : NEW_LINE INDENT if ( not t1 ) : NEW_LINE INDENT return t2 NEW_LINE DEDENT if ( not t2 ) : NEW_LINE INDENT return t1 NEW_LINE DEDENT t1 . data += t2 . data NEW_LINE t1 . left = MergeTrees ( t1 . left , t2 . left ) NEW_LINE t1 . right = MergeTrees ( t1 . right , t2 . right ) NEW_LINE return t1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 1 ) NEW_LINE root1 . left = newNode ( 2 ) NEW_LINE root1 . right = newNode ( 3 ) NEW_LINE root1 . left . left = newNode ( 4 ) NEW_LINE root1 . left . right = newNode ( 5 ) NEW_LINE root1 . right . right = newNode ( 6 ) NEW_LINE root2 = newNode ( 4 ) NEW_LINE root2 . left = newNode ( 1 ) NEW_LINE root2 . right = newNode ( 7 ) NEW_LINE root2 . left . left = newNode ( 3 ) NEW_LINE root2 . right . left = newNode ( 2 ) NEW_LINE root2 . right . right = newNode ( 6 ) NEW_LINE root3 = MergeTrees ( root1 , root2 ) NEW_LINE print ( " The ▁ Merged ▁ Binary ▁ Tree ▁ is : " ) NEW_LINE inorder ( root3 ) NEW_LINE DEDENT