Foldable Binary Trees |  ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; Returns true if the given tree can be folded ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; If both left and right subtrees are NULL , then return true ; If one of the trees is NULL and other is not , then return false ; Otherwise check if left and right subtrees are mirrors of their counterparts ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; The constructed binary tree is 1 / \ 2 3 \ / 4 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define bool  int NEW_LINE #define true  1 NEW_LINE #define false  0 NEW_LINE class node { public : int data ; node * left ; node * right ; } ; bool IsFoldableUtil ( node * n1 , node * n2 ) ; bool IsFoldable ( node * root ) { if ( root == NULL ) { return true ; } return IsFoldableUtil ( root -> left , root -> right ) ; } bool IsFoldableUtil ( node * n1 , node * n2 ) { if ( n1 == NULL && n2 == NULL ) { return true ; } if ( n1 == NULL n2 == NULL ) { return false ; } return IsFoldableUtil ( n1 -> left , n2 -> right ) && IsFoldableUtil ( n1 -> right , n2 -> left ) ; } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int main ( void ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; if ( IsFoldable ( root ) == true ) { cout << " Tree ▁ is ▁ foldable " ; } else { cout << " Tree ▁ is ▁ not ▁ foldable " ; } return 0 ; }