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

 1 class Solution {
 2 public:
 3     bool isSymmetric(TreeNode *root) {
 4         if(!root) return true;
 5         return isSymmetricRe(root->left, root->right);
 6     }
 7     
 8     bool isSymmetricRe(TreeNode* t1, TreeNode* t2)
 9     {
10         if(!t1 && !t2) return true;
11         if(!t1 || !t2 || t1->val != t2->val) return false;
12         return isSymmetricRe(t1->left, t2->right) && isSymmetricRe(t1->right, t2->left);
13     }
14 };

 

posted @ 2014-04-04 22:15  beehard  阅读(97)  评论(0编辑  收藏  举报