Given a binary tree, the task is to find out if the tree can be folded or not. A tree can be folded if the left and right subtrees of the tree are structure-wise mirror images of each other. An empty tree is considered foldable.
Examples:
Input:
Output: True Explanation: The above tree can be folded as left and right subtrees of the tree are structure-wise mirror images of each other.
Input:
Output: False Explanation: The above tree cannot be folded as left and right subtrees of the tree are not structure-wise mirror images of each other.
[Expected Approach - 1] By Changing Left Subtree to its Mirror - O(n) Time and O(h) Space
The idea is to change the left subtree to its mirror then compare the left subtree with the right subtree. First, convert the left subtree to its mirror image (for each node, swap its left and right nodes). Then compare the structure of left subtree and right subtree and store the result. Revert the left subtree and return the result.
C++
// C++ program to check foldable binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to convert subtree // into its mirror voidmirror(Node*root){if(root==nullptr)return;// Recursively process the left// and right subtrees.mirror(root->left);mirror(root->right);// swap the left and right nodes.Node*temp=root->left;root->left=root->right;root->right=temp;}// function to check if two trees have// same structureboolisStructSame(Node*a,Node*b){// If both subtrees are null, return // true.if(a==nullptr&&b==nullptr)returntrue;// If one of the subtrees is null,// return false.if(a==nullptr||b==nullptr)returnfalse;// check left and right subtree. returnisStructSame(a->left,b->left)&&isStructSame(a->right,b->right);}// Function to check if a tree is foldable.boolisFoldable(Node*root){if(root==nullptr)returntrue;// Convert left subtree into // its mirror.mirror(root->left);// Compare the left subtree // and right subtree.boolans=isStructSame(root->left,root->right);// Revert the left subtree.mirror(root->left);returnans;}intmain(){// The constructed binary tree is// 1// / \ // 2 3// \ /// 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(4);root->right->left=newNode(5);if(isFoldable(root)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
C
// C program to check foldable binary tree#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Function to convert subtree // into its mirror voidmirror(structNode*root){if(root==NULL)return;// Recursively process the left// and right subtrees.mirror(root->left);mirror(root->right);// swap the left and right nodes.structNode*temp=root->left;root->left=root->right;root->right=temp;}// function to check if two trees have// same structureintisStructSame(structNode*a,structNode*b){// If both subtrees are null, return // true.if(a==NULL&&b==NULL)return1;// If one of the subtrees is null,// return false.if(a==NULL||b==NULL)return0;// check left and right subtree. returnisStructSame(a->left,b->left)&&isStructSame(a->right,b->right);}// Function to check if a tree is foldable.intisFoldable(structNode*root){if(root==NULL)return1;// Convert left subtree into // its mirror.mirror(root->left);// Compare the left subtree // and right subtree.intans=isStructSame(root->left,root->right);// Revert the left subtree.mirror(root->left);returnans;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// The constructed binary tree is// 1// / \ // 2 3// \ /// 4 5structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->right=createNode(4);root->right->left=createNode(5);if(isFoldable(root)){printf("True\n");}else{printf("False\n");}return0;}
Java
// Java program to check foldable binary treeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to convert subtree // into its mirror staticvoidmirror(Noderoot){if(root==null)return;// Recursively process the left// and right subtrees.mirror(root.left);mirror(root.right);// swap the left and right nodes.Nodetemp=root.left;root.left=root.right;root.right=temp;}// function to check if two trees have// same structurestaticbooleanisStructSame(Nodea,Nodeb){// If both subtrees are null, return // true.if(a==null&&b==null)returntrue;// If one of the subtrees is null,// return false.if(a==null||b==null)returnfalse;// check left and right subtree. returnisStructSame(a.left,b.left)&&isStructSame(a.right,b.right);}// Function to check if a tree is foldable.staticbooleanisFoldable(Noderoot){if(root==null)returntrue;// Convert left subtree into // its mirror.mirror(root.left);// Compare the left subtree // and right subtree.booleanans=isStructSame(root.left,root.right);// Revert the left subtree.mirror(root.left);returnans;}publicstaticvoidmain(String[]args){// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python program to check foldable binary treeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to convert subtree # into its mirror defmirror(root):ifrootisNone:return# Recursively process the left# and right subtrees.mirror(root.left)mirror(root.right)# swap the left and right nodes.root.left,root.right=root.right,root.left# function to check if two trees have# same structuredefisStructSame(a,b):# If both subtrees are null, return # true.ifaisNoneandbisNone:returnTrue# If one of the subtrees is null,# return false.ifaisNoneorbisNone:returnFalse# check left and right subtree.returnisStructSame(a.left,b.left)and \
isStructSame(a.right,b.right)# Function to check if a tree is foldable.defisFoldable(root):ifrootisNone:returnTrue# Convert left subtree into # its mirror.mirror(root.left)# Compare the left subtree # and right subtree.ans=isStructSame(root.left,root.right)# Revert the left subtree.mirror(root.left)returnansif__name__=="__main__":# The constructed binary tree is# 1# / \# 2 3# \ /# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(4)root.right.left=Node(5)ifisFoldable(root):print("True")else:print("False")
C#
// C# program to check foldable binary treeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to convert subtree // into its mirror staticvoidMirror(Noderoot){if(root==null)return;// Recursively process the left// and right subtrees.Mirror(root.left);Mirror(root.right);// swap the left and right nodes.Nodetemp=root.left;root.left=root.right;root.right=temp;}// function to check if two trees have// same structurestaticboolIsStructSame(Nodea,Nodeb){// If both subtrees are null, return // true.if(a==null&&b==null)returntrue;// If one of the subtrees is null,// return false.if(a==null||b==null)returnfalse;// check left and right subtree. returnIsStructSame(a.left,b.left)&&IsStructSame(a.right,b.right);}// Function to check if a tree is foldable.staticboolisFoldable(Noderoot){if(root==null)returntrue;// Convert left subtree into // its mirror.Mirror(root.left);// Compare the left subtree // and right subtree.boolans=IsStructSame(root.left,root.right);// Revert the left subtree.Mirror(root.left);returnans;}staticvoidMain(){// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to check foldable binary treeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to convert subtree // into its mirror functionmirror(root){if(root===null)return;// Recursively process the left// and right subtrees.mirror(root.left);mirror(root.right);// swap the left and right nodes.lettemp=root.left;root.left=root.right;root.right=temp;}// function to check if two trees have// same structurefunctionisStructSame(a,b){// If both subtrees are null, return // true.if(a===null&&b===null)returntrue;// If one of the subtrees is null,// return false.if(a===null||b===null)returnfalse;// check left and right subtree. returnisStructSame(a.left,b.left)&&isStructSame(a.right,b.right);}// Function to check if a tree is foldable.functionisFoldable(root){if(root===null)returntrue;// Convert left subtree into // its mirror.mirror(root.left);// Compare the left subtree // and right subtree.letans=isStructSame(root.left,root.right);// Revert the left subtree.mirror(root.left);returnans;}// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){console.log("True");}else{console.log("False");}
Output
True
[Expected Approach - 2] By Comparing Subtree Nodes Recursively - O(n) Time and O(h) Space
The idea is to recursively check if the left and right subtree are mirror or not. For each node a (of left subtree) and b (of right subtree), recursively compare the left subtree of a with right subtree of b and compare the right subtree of a with left subtree of b. If both are mirror structures, return true. Otherwise, return false.
C++
// C++ program to check foldable binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// function to check if two trees are // mirrors boolisFoldableRecur(Node*a,Node*b){// If both subtrees are null, return // true.if(a==nullptr&&b==nullptr)returntrue;// If one of the subtrees is null,// return false.if(a==nullptr||b==nullptr)returnfalse;// Compare left subtree of tree 'a' with // right subtree of tree 'b' and compare // right subtree of tree 'a' with left // subtree of tree 'b'.returnisFoldableRecur(a->left,b->right)&&isFoldableRecur(a->right,b->left);}// Function to check if a tree is foldable.boolisFoldable(Node*root){if(root==nullptr)returntrue;returnisFoldableRecur(root->left,root->right);}intmain(){// The constructed binary tree is// 1// / \ // 2 3// \ /// 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(4);root->right->left=newNode(5);if(isFoldable(root)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
C
// C program to check foldable binary tree#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// function to check if two trees are // mirrors intisFoldableRecur(structNode*a,structNode*b){// If both subtrees are null, return // true.if(a==NULL&&b==NULL)return1;// If one of the subtrees is null,// return false.if(a==NULL||b==NULL)return0;// Compare left subtree of tree 'a' with // right subtree of tree 'b' and compare // right subtree of tree 'a' with left // subtree of tree 'b'.returnisFoldableRecur(a->left,b->right)&&isFoldableRecur(a->right,b->left);}// Function to check if a tree is foldable.intisFoldable(structNode*root){if(root==NULL)return1;returnisFoldableRecur(root->left,root->right);}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// The constructed binary tree is// 1// / \ // 2 3// \ /// 4 5structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->right=createNode(4);root->right->left=createNode(5);if(isFoldable(root)){printf("True\n");}else{printf("False\n");}return0;}
Java
// Java program to check foldable binary treeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// function to check if two trees are // mirrors staticbooleanisFoldableRecur(Nodea,Nodeb){// If both subtrees are null, return // true.if(a==null&&b==null)returntrue;// If one of the subtrees is null,// return false.if(a==null||b==null)returnfalse;// Compare left subtree of tree 'a' with // right subtree of tree 'b' and compare // right subtree of tree 'a' with left // subtree of tree 'b'.returnisFoldableRecur(a.left,b.right)&&isFoldableRecur(a.right,b.left);}// Function to check if a tree is foldable.staticbooleanisFoldable(Noderoot){if(root==null)returntrue;returnisFoldableRecur(root.left,root.right);}publicstaticvoidmain(String[]args){// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python program to check foldable binary treeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# function to check if two trees are # mirrors defisFoldableRecur(a,b):# If both subtrees are null, return # true.ifaisNoneandbisNone:returnTrue# If one of the subtrees is null,# return false.ifaisNoneorbisNone:returnFalse# Compare left subtree of tree 'a' with # right subtree of tree 'b' and compare # right subtree of tree 'a' with left # subtree of tree 'b'.returnisFoldableRecur(a.left,b.right)andisFoldableRecur(a.right,b.left)# Function to check if a tree is foldable.defisFoldable(root):ifrootisNone:returnTruereturnisFoldableRecur(root.left,root.right)if__name__=="__main__":# The constructed binary tree is# 1# / \# 2 3# \ /# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(4)root.right.left=Node(5)ifisFoldable(root):print("True")else:print("False")
C#
// C# program to check foldable binary treeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// function to check if two trees are // mirrors staticboolisFoldableRecur(Nodea,Nodeb){// If both subtrees are null, return // true.if(a==null&&b==null)returntrue;// If one of the subtrees is null,// return false.if(a==null||b==null)returnfalse;// Compare left subtree of tree 'a' with // right subtree of tree 'b' and compare // right subtree of tree 'a' with left // subtree of tree 'b'.returnisFoldableRecur(a.left,b.right)&&isFoldableRecur(a.right,b.left);}// Function to check if a tree is foldable.staticboolisFoldable(Noderoot){if(root==null)returntrue;returnisFoldableRecur(root.left,root.right);}staticvoidMain(){// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to check foldable binary treeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// function to check if two trees are // mirrors functionisFoldableRecur(a,b){// If both subtrees are null, return // true.if(a===null&&b===null)returntrue;// If one of the subtrees is null,// return false.if(a===null||b===null)returnfalse;// Compare left subtree of tree 'a' with // right subtree of tree 'b' and compare // right subtree of tree 'a' with left // subtree of tree 'b'.returnisFoldableRecur(a.left,b.right)&&isFoldableRecur(a.right,b.left);}// Function to check if a tree is foldable.functionisFoldable(root){if(root===null)returntrue;returnisFoldableRecur(root.left,root.right);}// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){console.log("True");}else{console.log("False");}
Output
True
[Expected Approach - 3] Using Breadth first Search - O(n) Time and O(n) Space
The idea is to use Queue for traversing the tree and using the BFS approach. Push the left node and right node of the root into a queue. While queue is not empty, pop two nodes, a (left subtree node)and b (right subtree node). If both are null nodes, continue. If one of them is null, return false. Push the left node of a with the right node of b, and push the right node of a with the left node of b. If queue becomes empty, return true.
C++
// C++ program to check foldable binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to check if a tree is foldable.boolisFoldable(Node*root){if(root==nullptr)returntrue;queue<Node*>q;q.push(root->left);q.push(root->right);while(!q.empty()){Node*a=q.front();q.pop();Node*b=q.front();q.pop();// If both subtrees are null, continue.if(a==nullptr&&b==nullptr)continue;// If one of the subtrees is null,// return false.if(a==nullptr||b==nullptr)returnfalse;// Push left node of a and right // node of b.q.push(a->left);q.push(b->right);// Push right node of b and left // node of a.q.push(a->right);q.push(b->left);}returntrue;}intmain(){// The constructed binary tree is// 1// / \ // 2 3// \ /// 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(4);root->right->left=newNode(5);if(isFoldable(root)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
Java
// Java program to check foldable binary treeimportjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to check if a tree is foldable.staticbooleanisFoldable(Noderoot){if(root==null)returntrue;Queue<Node>q=newLinkedList<>();q.add(root.left);q.add(root.right);while(!q.isEmpty()){Nodea=q.poll();Nodeb=q.poll();// If both subtrees are null, continue.if(a==null&&b==null)continue;// If one of the subtrees is null,// return false.if(a==null||b==null)returnfalse;// Push left node of a and right// node of b.q.add(a.left);q.add(b.right);// Push right node of a and left// node of b.q.add(a.right);q.add(b.left);}returntrue;}publicstaticvoidmain(String[]args){// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python program to check foldable binary treefromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to check if a tree is foldable.defisFoldable(root):ifrootisNone:returnTrueq=deque([root.left,root.right])whileq:a=q.popleft()b=q.popleft()# If both subtrees are null, continue.ifaisNoneandbisNone:continue# If one of the subtrees is null,# return false.ifaisNoneorbisNone:returnFalse# Push left node of a and right# node of b.q.append(a.left)q.append(b.right)# Push right node of a and left# node of b.q.append(a.right)q.append(b.left)returnTrueif__name__=="__main__":# The constructed binary tree is# 1# / \# 2 3# \ /# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(4)root.right.left=Node(5)ifisFoldable(root):print("True")else:print("False")
C#
// C# program to check foldable binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to check if a tree is foldable.staticboolisFoldable(Noderoot){if(root==null)returntrue;Queue<Node>q=newQueue<Node>();q.Enqueue(root.left);q.Enqueue(root.right);while(q.Count>0){Nodea=q.Dequeue();Nodeb=q.Dequeue();// If both subtrees are null, continue.if(a==null&&b==null)continue;// If one of the subtrees is null,// return false.if(a==null||b==null)returnfalse;// Push left node of a and right// node of b.q.Enqueue(a.left);q.Enqueue(b.right);// Push right node of a and left// node of b.q.Enqueue(a.right);q.Enqueue(b.left);}returntrue;}staticvoidMain(string[]args){// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to check foldable // binary treeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to check if a tree is foldable.functionisFoldable(root){if(root===null)returntrue;letq=[];q.push(root.left);q.push(root.right);while(q.length){leta=q.shift();letb=q.shift();// If both subtrees are null, continue.if(a===null&&b===null)continue;// If one of the subtrees is null,// return false.if(a===null||b===null)returnfalse;// Push left node of a and right// node of b.q.push(a.left);q.push(b.right);// Push right node of a and left// node of b.q.push(a.right);q.push(b.left);}returntrue;}// The constructed binary tree is// 1// / \// 2 3// \ /// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);if(isFoldable(root)){console.log("True");}else{console.log("False");}