Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find two Binary Tree are structurally identical

I was recently asked in the interview

What would be the efficient algorithm to find if two given binary trees are structurally identical but not the content?

  a 
/   \
b    c
      \ 
       e

  z 
/   \
u    v
      \ 
       t

are structurally identical.

Next question was find out if 2 binary tree are structurally mirror ?

Any pointer or help are appreciated.

My attempt was

boolean isStrucutrallyIdentitical(BinaryNode root1, BinayNode root2)  {  
   if(root1==null && root2==null) return true;
   if(root1==null || root2==null) return false;
   if(root1!=null && roo2!=null) return true; // instead of value just check if its null or not 
   return isStrucutrallyIdentitical(root1.getLeft(), root2.getLeft()) &&  isStrucutrallyIdentitical(root1.getRight(), root2.getRight()); 
} 
like image 538
plzdontkillme Avatar asked Dec 01 '25 02:12

plzdontkillme


1 Answers

public boolean areStructuralySame(TreeNode<Integer> tree1, TreeNode<Integer> tree2) {
    if(tree1 == null && tree2 == null) {
        return true;
    }
    if(tree1 == null || tree2 == null) {
        return false;
    } else return (areStructuralySame(tree1.getLeft(), tree2.getLeft()) && areStructuralySame(tree1.getRight(), tree2.getRight()));

}

This works fine

like image 169
plzdontkillme Avatar answered Dec 04 '25 01:12

plzdontkillme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!