Sunday, September 1, 2013

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following is not:



    1
   / \
  2   2
   \   \
   3    3
bool isSymmetric(TreeNode *root1, TreeNode *root2)
{
   if(!root1 && !root2)
       return true;
   if(!root1 || !root2)
        return false;
    if(root1->val != root2->val)
        return false;
    
    return isSymmetric(root1->left, root2->right) && isSymmetric(root1->right, root2->left);
}

bool isSymmetric(TreeNode *root) {
 
    if(!root)
        return true;
    return isSymmetric(root->left, root->right);
}

No comments:

Post a Comment