package problems.geeks.tree;
/**
* Foldable Binary Trees
*
* http://www.geeksforgeeks.org/foldable-binary-trees/
*
* Question: Given a binary tree, find out if the tree can be folded or not.
*
* A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable.
*
* Consider the below trees:
* (a) and (b) can be folded.
* (c) and (d) cannot be folded.
*
* (a)
* 10
* / \
* 7 15
* \ /
* 9 11
*
* (b)
* 10
* / \
* 7 15
* / \
* 9 11
*
* (c)
* 10
* / \
* 7 15
* / /
* 5 11
*
* (d)
*
* 10
* / \
* 7 15
* / \ /
* 9 10 12
*/
import java.util.*;
import adt.tree.Tree;
import adt.tree.TreeNode;
public class Q023_Foldable_Binary_Trees {
public static void main(String[] args) {
TreeNode root = Tree.tree1();
boolean res = isFoldable(root);
System.out.println(res);
}
static boolean isFoldable(TreeNode root) {
if (root == null) {
return true;
}
return isMirror(root.left, root.right);
}
static boolean isMirror(TreeNode a, TreeNode b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
return isMirror(a.left, b.right) && isMirror(a.right, b.left);
}
}