VOOZH about

URL: https://www.geeksforgeeks.org/dsa/foldable-binary-trees/

⇱ Foldable Binary Trees - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Foldable Binary Trees

Last Updated : 23 Jul, 2025

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.


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.


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.


Output
True
Comment
Article Tags:
Article Tags: