Sunday, July 14, 2013

Check if a binary tree is symmetric

Problem:
Check if a given binary tree is symmetric.

Solution:

public boolean recurseSymmetry(Node<AnyType> left, Node<AnyType> right ){
   if(left == null || right == null) return left==right;
   else 
      return left.value == right.value &&
             recurseSymmetry(left.left, right.right) &&
             recurseSymmetry(left.right, right.left);
}


Complexity:
time - O(n)
space - O(n) (for recursion stack)
Links and credits:
http://www.careercup.com/question?id=20884671

No comments:

Post a Comment