首页 > 其他 > 详细

【leetcode】Symmetric Tree

时间:2015-07-07 18:43:22      阅读:255      评论: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

 

思路:判断树是否是对称的 递归判断即可

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(NULL == root)   return true;

        TreeNode * L = root->left;
        TreeNode * R = root->right;
        return isSymmetricPart(L, R);
    }

     bool isSymmetricPart(TreeNode* L, TreeNode* R)
     {
         if(NULL == L && NULL == R) return true;
         if(NULL == L && NULL != R || NULL == R && NULL != L) return false;
         if(L->val == R->val)
             return isSymmetricPart(L->left, R->right) && isSymmetricPart(L->right, R->left);
         else
             return false;
         
     }
};

 

更简短的写法

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return !root ? true : isSymmetricHelper(root->left, root->right);
    }

    bool isSymmetricHelper(TreeNode* left, TreeNode* right) {
        if (!left && !right) { return true; }
        return 
            (left && right) &&
            (left->val == right->val) &&
            isSymmetricHelper(left->left, right->right) &&
            isSymmetricHelper(left->right, right->left);
    }
};

 

【leetcode】Symmetric Tree

原文:http://www.cnblogs.com/dplearning/p/4627307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!