码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Symmetric Tree

时间:2015-05-02 11:06:18      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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 isSym(TreeNode* n1,TreeNode* n2)
 4     {
 5         if(n1==NULL&&n2!=NULL) return false;
 6         if(n1!=NULL&&n2==NULL) return false;
 7         if(n1==NULL&&n2==NULL) return true;
 8         if(n1->val!=n2->val) return false;
 9 
10         return isSym(n1->left,n2->right)&&isSym(n1->right,n2->left);
11     }
12 
13     bool isSymmetric(TreeNode* root) {
14         if(root==NULL||(!root->left&&!root->right)) return true;
15         return isSym(root->left,root->right);
16     }
17 };

 

【leetcode】Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4471624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!