Construct a Maximum Binary Tree from two given Binary Trees | C ++ program to find the Maximum Binary Tree from two Binary Trees ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper method that allocates a new node with the given data and NULL left and right pointers . ; Given a binary tree , print its nodes in inorder ; First recur on left child ; Then print the data of node ; Now recur on right child ; Method to find the maximum binary tree from two binary trees ; Driver Code ; First Binary Tree 3 / \ 2 6 / 20 ; Second Binary Tree 5 / \ 1 8 \ \ 2 8
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int data , Node * left , Node * right ) { this -> data = data ; this -> left = left ; this -> right = right ; } } ; Node * newNode ( int data ) { Node * tmp = new Node ( data , NULL , NULL ) ; return tmp ; } void inorder ( Node * node ) { if ( node == NULL ) return ; inorder ( node -> left ) ; cout << node -> data << " ▁ " ; inorder ( node -> right ) ; } Node * MaximumBinaryTree ( Node * t1 , Node * t2 ) { if ( t1 == NULL ) return t2 ; if ( t2 == NULL ) return t1 ; t1 -> data = max ( t1 -> data , t2 -> data ) ; t1 -> left = MaximumBinaryTree ( t1 -> left , t2 -> left ) ; t1 -> right = MaximumBinaryTree ( t1 -> right , t2 -> right ) ; return t1 ; } int main ( ) { Node * root1 = newNode ( 3 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 6 ) ; root1 -> left -> left = newNode ( 20 ) ; Node * root2 = newNode ( 5 ) ; root2 -> left = newNode ( 1 ) ; root2 -> right = newNode ( 8 ) ; root2 -> left -> right = newNode ( 2 ) ; root2 -> right -> right = newNode ( 8 ) ; Node * root3 = MaximumBinaryTree ( root1 , root2 ) ; inorder ( root3 ) ; }