Tuesday, 11 October 2016

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
Solution:
public class IsFoldabletree {
 Node root;
 public boolean isFoldabel(Node root2)
 {
  if(root2==null)
   return true;
  return isMirrorLeftNRight(root2.left,root2.right);
  
 }
 private boolean isMirrorLeftNRight(Node left, Node right) {
  if(left==null && right==null)
   return true;
  if(left==null || right==null)
   return false;
  
  // TODO Auto-generated method stub
  return isMirrorLeftNRight(left.left, right.right)&&isMirrorLeftNRight(left.right, right.left);
 }
 public static void main(String[] args) {
  IsFoldabletree tree=new IsFoldabletree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.right.left = new Node(4);
        tree.root.left.right = new Node(5);
        if(tree.isFoldabel(tree.root))
         System.out.println("Tree is foldable");
        else
         System.out.println("Tree is not foldable");
  
 }

}

No comments:

Post a Comment