Wednesday, April 24, 2013

Leetcode: Symmetric Tree in C++



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
Note:
Bonus points if you could solve it both recursively and iteratively.

Solution: recursively 
bool helper(TreeNode *first, TreeNode* second)
    {
        if(!first&&!second)
        return true;
        else if(first&&second)
        {
            if(first->val!=second->val)
            return false;
            return helper(first->left,second->right)&&helper(first->right,second->left);
        }
        else
        return false;
    }
    bool isSymmetric(TreeNode *root) {
        if(!root)
        return true;
        return helper(root->left,root->right);
    }

No comments:

Post a Comment