Interview Questions

Software Engineer In Manager round: Check given tree is symmetric or not ?

Manager Round interview Questions and Answers


(Continued from previous question...)

Software Engineer In Manager round: Check given tree is symmetric or not ?

<round3> ( Manager round )
7. Check given tree is symmetric or not ?

e.g


1) Symmetric
1
/ \
2 2
/ \
3 3
2) non-symmetric
1
/ \
2 3



An1
boolean isSymetry(Node root) {
return isSymetry(root.right, root.left);
}

boolean isSymetry(Node n1, Node n2) {
if(n1 == null && n2 == null) {
return true;
}
if(n1 != null && n2 != null) {
return n1.data == n2.data && isSymetry(n1.right, n2.left) && isSymetry(n1.left, n2.right);
}
return false;
}



An2
booolean isSymmetric(node n)
{
return isMirrorImage(n,n);
}
boolean isMirrorImage(node n1,node n2)
{
if(n1==null && n2==null)
return true;
else if(n1!=null || n2!=null)
return false;
else if(n1.val !=n2.val)
return false;
else
return isMirrorImage(n1.left,n2.right) && isMirrorImage(n1.right,n2.left);

(Continued on next question...)

Other Interview Questions