Open In App

Foldable Binary Trees

Last Updated : 06 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

foldable-binary-trees


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: 

foldable-binary-trees-2

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>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to convert subtree 
// into its mirror 
void mirror(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 structure
bool isStructSame(Node* a, Node* b) {
    
    // If both subtrees are null, return 
    // true.
    if (a == nullptr && b == nullptr)
        return true;
        
    // If one of the subtrees is null,
    // return false.
    if (a == nullptr || b == nullptr) 
        return false;
    
    // check left and right subtree.    
    return isStructSame(a->left, b->left) 
    &&
    isStructSame(a->right, b->right);
}

// Function to check if a tree is foldable.
bool isFoldable(Node* root) {
    if (root == nullptr) 
        return true;
        
    // Convert left subtree into 
    // its mirror.
    mirror(root->left);
    
    // Compare the left subtree 
    // and right subtree.
    bool ans = isStructSame(root->left, root->right);
    
    // Revert the left subtree.
    mirror(root->left);
    
    return ans;
}

int main() {
    
    // The constructed binary tree is
    //      1
    //     / \
    //     2 3
    //     \ /
    //     4 5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->right = new Node(4);
    root->right->left = new Node(5);

    if (isFoldable(root)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    return 0;
}
C
// C program to check foldable binary tree
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to convert subtree 
// into its mirror 
void mirror(struct Node* root) {
    if (root == NULL) return;

    // Recursively process the left
    // and right subtrees.
    mirror(root->left);
    mirror(root->right);

    // swap the left and right nodes.
    struct Node* temp = root->left;
    root->left = root->right;
    root->right = temp;
}

// function to check if two trees have
// same structure
int isStructSame(struct Node* a, struct Node* b) {

    // If both subtrees are null, return 
    // true.
    if (a == NULL && b == NULL)
        return 1;

    // If one of the subtrees is null,
    // return false.
    if (a == NULL || b == NULL)
        return 0;

    // check left and right subtree.    
    return isStructSame(a->left, b->left) 
    && 
    isStructSame(a->right, b->right);
}

// Function to check if a tree is foldable.
int isFoldable(struct Node* root) {
    if (root == NULL)
        return 1;

    // Convert left subtree into 
    // its mirror.
    mirror(root->left);

    // Compare the left subtree 
    // and right subtree.
    int ans = isStructSame(root->left, root->right);

    // Revert the left subtree.
    mirror(root->left);

    return ans;
}

struct Node* createNode(int x) {
    struct Node* newNode = 
    	(struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {

    // The constructed binary tree is
    //      1
    //     / \
    //     2  3
    //     \  /
    //     4 5
    struct Node* 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");
    }

    return 0;
}
Java
// Java program to check foldable binary tree
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to convert subtree 
    // into its mirror 
    static void mirror(Node root) {
        if (root == null) 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 structure
    static boolean isStructSame(Node a, Node b) {

        // If both subtrees are null, return 
        // true.
        if (a == null && b == null)
            return true;

        // If one of the subtrees is null,
        // return false.
        if (a == null || b == null)
            return false;

        // check left and right subtree.    
        return isStructSame(a.left, b.left)
            && 
            isStructSame(a.right, b.right);
    }

    // Function to check if a tree is foldable.
    static boolean isFoldable(Node root) {
        if (root == null)
            return true;

        // Convert left subtree into 
        // its mirror.
        mirror(root.left);

        // Compare the left subtree 
        // and right subtree.
        boolean ans = isStructSame(root.left, root.right);

        // Revert the left subtree.
        mirror(root.left);

        return ans;
    }

    public static void main(String[] args) {

        // The constructed binary tree is
        //      1
        //     / \
        //     2  3
        //     \  /
        //     4 5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(5);

        if (isFoldable(root)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check foldable binary tree

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to convert subtree 
# into its mirror 
def mirror(root):
    if root is None:
        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 structure
def isStructSame(a, b):
    
    # If both subtrees are null, return 
    # true.
    if a is None and b is None:
        return True
    
    # If one of the subtrees is null,
    # return false.
    if a is None or b is None:
        return False
    
    # check left and right subtree.
    return isStructSame(a.left, b.left) and \
  	isStructSame(a.right, b.right)

# Function to check if a tree is foldable.
def isFoldable(root):
    if root is None:
        return True

    # 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)

    return ans

if __name__ == "__main__":

    # The constructed binary tree is
    #      1
    #     / \
    #     2  3
    #     \  /
    #     4 5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.right = Node(4)
    root.right.left = Node(5)

    if isFoldable(root):
        print("True")
    else:
        print("False")
C#
// C# program to check foldable binary tree
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to convert subtree 
    // into its mirror 
    static void Mirror(Node root) {
        if (root == null) 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 structure
    static bool IsStructSame(Node a, Node b) {

        // If both subtrees are null, return 
        // true.
        if (a == null && b == null)
            return true;

        // If one of the subtrees is null,
        // return false.
        if (a == null || b == null)
            return false;

        // check left and right subtree.    
        return IsStructSame(a.left, b.left)
            && 
            IsStructSame(a.right, b.right);
    }

    // Function to check if a tree is foldable.
    static bool isFoldable(Node root) {
        if (root == null)
            return true;

        // Convert left subtree into 
        // its mirror.
        Mirror(root.left);

        // Compare the left subtree 
        // and right subtree.
        bool ans = IsStructSame(root.left, root.right);

        // Revert the left subtree.
        Mirror(root.left);

        return ans;
    }

    static void Main() {

        // The constructed binary tree is
        //      1
        //     / \
        //     2  3
        //     \  /
        //     4 5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(5);

        if (isFoldable(root)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check foldable binary tree

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to convert subtree 
// into its mirror 
function mirror(root) {
    if (root === null) return;

    // Recursively process the left
    // and right subtrees.
    mirror(root.left);
    mirror(root.right);

    // swap the left and right nodes.
    let temp = root.left;
    root.left = root.right;
    root.right = temp;
}

// function to check if two trees have
// same structure
function isStructSame(a, b) {

    // If both subtrees are null, return 
    // true.
    if (a === null && b === null)
        return true;

    // If one of the subtrees is null,
    // return false.
    if (a === null || b === null)
        return false;

    // check left and right subtree.    
    return isStructSame(a.left, b.left) 
        && 
        isStructSame(a.right, b.right);
}

// Function to check if a tree is foldable.
function isFoldable(root) {
    if (root === null)
        return true;

    // Convert left subtree into 
    // its mirror.
    mirror(root.left);

    // Compare the left subtree 
    // and right subtree.
    let ans = isStructSame(root.left, root.right);

    // Revert the left subtree.
    mirror(root.left);

    return ans;
}

// The constructed binary tree is
//      1
//     / \
//     2   3
//     \  /
//     4 5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(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>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// function to check if two trees are 
// mirrors 
bool isFoldableRecur(Node* a, Node* b) {
    
    // If both subtrees are null, return 
    // true.
    if (a == nullptr && b == nullptr)
        return true;
        
    // If one of the subtrees is null,
    // return false.
    if (a == nullptr || b == nullptr) 
        return false;
    
    // 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'.
    return isFoldableRecur(a->left, b->right) 
    &&
    isFoldableRecur(a->right, b->left);
}

// Function to check if a tree is foldable.
bool isFoldable(Node* root) {
    if (root == nullptr) 
        return true;
        
    return isFoldableRecur(root->left, root->right);
}

int main() {
    
    // The constructed binary tree is
    //      1
    //     / \
    //     2 3
    //     \ /
    //     4 5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->right = new Node(4);
    root->right->left = new Node(5);

    if (isFoldable(root)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    return 0;
}
C
// C program to check foldable binary tree
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// function to check if two trees are 
// mirrors 
int isFoldableRecur(struct Node* a, struct Node* b) {

    // If both subtrees are null, return 
    // true.
    if (a == NULL && b == NULL)
        return 1;

    // If one of the subtrees is null,
    // return false.
    if (a == NULL || b == NULL)
        return 0;

    // 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'.
    return isFoldableRecur(a->left, b->right)
        && isFoldableRecur(a->right, b->left);
}

// Function to check if a tree is foldable.
int isFoldable(struct Node* root) {
    if (root == NULL)
        return 1;

    return isFoldableRecur(root->left, root->right);
}

struct Node* createNode(int x) {
    struct Node* newNode = 
    (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {

    // The constructed binary tree is
    //      1
    //     / \
    //     2 3
    //     \ /
    //     4 5
    struct Node* 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");
    }

    return 0;
}
Java
// Java program to check foldable binary tree
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // function to check if two trees are 
    // mirrors 
    static boolean isFoldableRecur(Node a, Node b) {

        // If both subtrees are null, return 
        // true.
        if (a == null && b == null)
            return true;

        // If one of the subtrees is null,
        // return false.
        if (a == null || b == null)
            return false;

        // 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'.
        return isFoldableRecur(a.left, b.right) &&
                isFoldableRecur(a.right, b.left);
    }

    // Function to check if a tree is foldable.
    static boolean isFoldable(Node root) {
        if (root == null)
            return true;

        return isFoldableRecur(root.left, root.right);
    }

    public static void main(String[] args) {

        // The constructed binary tree is
        //      1
        //     / \
        //     2 3
        //     \ /
        //     4 5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(5);

        if (isFoldable(root)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check foldable binary tree

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# function to check if two trees are 
# mirrors 
def isFoldableRecur(a, b):
    
    # If both subtrees are null, return 
    # true.
    if a is None and b is None:
        return True
    
    # If one of the subtrees is null,
    # return false.
    if a is None or b is None:
        return False
    
    # 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'.
    return isFoldableRecur(a.left, b.right) and isFoldableRecur(a.right, b.left)

# Function to check if a tree is foldable.
def isFoldable(root):
    if root is None:
        return True
    
    return isFoldableRecur(root.left, root.right)

if __name__ == "__main__":

    # The constructed binary tree is
    #      1
    #     / \
    #     2 3
    #     \ /
    #     4 5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.right = Node(4)
    root.right.left = Node(5)

    if isFoldable(root):
        print("True")
    else:
        print("False")
C#
// C# program to check foldable binary tree
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // function to check if two trees are 
	// mirrors 
    static bool isFoldableRecur(Node a, Node b) {

        // If both subtrees are null, return 
        // true.
        if (a == null && b == null)
            return true;

        // If one of the subtrees is null,
        // return false.
        if (a == null || b == null)
            return false;

        // 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'.
        return isFoldableRecur(a.left, b.right)
            && isFoldableRecur(a.right, b.left);
    }

    // Function to check if a tree is foldable.
    static bool isFoldable(Node root) {
        if (root == null)
            return true;

        return isFoldableRecur(root.left, root.right);
    }

    static void Main() {

        // The constructed binary tree is
        //      1
        //     / \
        //     2 3
        //     \ /
        //     4 5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(5);

        if (isFoldable(root)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check foldable binary tree

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// function to check if two trees are 
// mirrors 
function isFoldableRecur(a, b) {

    // If both subtrees are null, return 
    // true.
    if (a === null && b === null)
        return true;

    // If one of the subtrees is null,
    // return false.
    if (a === null || b === null)
        return false;

    // 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'.
    return isFoldableRecur(a.left, b.right)
        && isFoldableRecur(a.right, b.left);
}

// Function to check if a tree is foldable.
function isFoldable(root) {
    if (root === null)
        return true;

    return isFoldableRecur(root.left, root.right);
}

// The constructed binary tree is
//      1
//     / \
//     2   3
//     \   /
//     4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(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>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to check if a tree is foldable.
bool isFoldable(Node* root) {
    if (root == nullptr) 
        return true;
        
    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)
            return false;
            
        // 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);
    }
    
    return true;
}

int main() {
    
    // The constructed binary tree is
    //      1
    //     / \
    //     2 3
    //     \ /
    //     4 5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->right = new Node(4);
    root->right->left = new Node(5);

    if (isFoldable(root)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to check foldable binary tree
import java.util.LinkedList;
import java.util.Queue;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to check if a tree is foldable.
    static boolean isFoldable(Node root) {
        if (root == null)
            return true;

        Queue<Node> q = new LinkedList<>();
        q.add(root.left);
        q.add(root.right);

        while (!q.isEmpty()) {
            Node a = q.poll();
            Node b = 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)
                return false;

            // 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);
        }

        return true;
    }

    public static void main(String[] args) {

        // The constructed binary tree is
        //      1
        //     / \
        //     2   3
        //     \   /
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(5);

        if (isFoldable(root)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check foldable binary tree
from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to check if a tree is foldable.
def isFoldable(root):
    if root is None:
        return True

    q = deque([root.left, root.right])

    while q:
        a = q.popleft()
        b = q.popleft()

        # If both subtrees are null, continue.
        if a is None and b is None:
            continue

        # If one of the subtrees is null,
        # return false.
        if a is None or b is None:
            return False

        # 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)

    return True

if __name__ == "__main__":

    # The constructed binary tree is
    #      1
    #     / \
    #     2   3
    #     \   /
    #     4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.right = Node(4)
    root.right.left = Node(5)

    if isFoldable(root):
        print("True")
    else:
        print("False")
C#
// C# program to check foldable binary tree
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to check if a tree is foldable.
    static bool isFoldable(Node root) {
        if (root == null)
            return true;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root.left);
        q.Enqueue(root.right);

        while (q.Count > 0) {
            Node a = q.Dequeue();
            Node b = 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)
                return false;

            // 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);
        }

        return true;
    }

    static void Main(string[] args) {

        // The constructed binary tree is
        //      1
        //     / \
        //     2   3
        //     \   /
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(5);

        if (isFoldable(root)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check foldable 
// binary tree

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to check if a tree is foldable.
function isFoldable(root) {
    if (root === null)
        return true;

    let q = [];
    q.push(root.left);
    q.push(root.right);

    while (q.length) {
        let a = q.shift();
        let b = 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)
            return false;

        // 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);
    }

    return true;
}

// The constructed binary tree is
//      1
//     / \
//     2   3
//     \   /
//     4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);

if (isFoldable(root)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Next Article
Article Tags :
Practice Tags :

Similar Reads