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

leetcode_101_Symmetric Tree

时间:2015-02-17 10:26:42      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   tree   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(root==NULL)
            return true;
        return isSymmetricUtil(root->left , root->right);
    }
    bool isSymmetricUtil(TreeNode *root1 , TreeNode *root2)
    {
        if(root1==NULL || root2==NULL)
            return root1==NULL && root2==NULL;
        if(root1->val == root2->val)
            return isSymmetricUtil(root1->left, root2->right) && isSymmetricUtil(root1->right , root2->left);
        else
            return false;
    }
};


//其他写法
class Solution {
public:
    bool isSymmetricUtil(TreeNode* root1, TreeNode* root2)
    {
        if(root1 == NULL && root2 == NULL) return true;
        if(root1 == NULL && root2 != NULL) return false;
        if(root1 != NULL && root2 == NULL) return false;
        return root1->val == root2->val && isSymmetricUtil(root1->left, root2->right) && isSymmetricUtil(root1->right, root2->left);
    }
    bool isSymmetric(TreeNode *root) {
        if(root == NULL) return true;
        return isSymmetricUtil(root->left, root->right);
    }
};


leetcode_101_Symmetric Tree

标签:leetcode   c++   tree   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43865257

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