LeetCode: Symmetric Tree


Title:

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

/**
 * Definition for a binary tree node.
 * 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 fun(root->left,root->right);
        
    }
    bool fun(TreeNode* p1, TreeNode* p2){
        if (!p1 && !p2 )
            return true;
        if (!p1 || !p2 )
            return false;
        return (p1->val == p2->val) && fun(p1->left,p2->right) && fun(p1->right,p2->left);
        
    }
};
/**
 * Definition for a binary tree node.
 * 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;
        stack<TreeNode* > s;
        s.push(root->left);
        s.push(root->right);
        while (!s.empty()){
            TreeNode* p1 = s.top();
            s.pop();
            TreeNode* p2 = s.top();
            s.pop();
            if (!p1 && !p2)
                continue;
            if (!p1 || !p2)
                return false;
            if (p1->val != p2->val)
                return false;
            s.push(p1->left);
            s.push(p2->right);
            s.push(p1->right);
            s.push(p2->left);
        }
        return true;
    }
    
};

优质内容筛选与推荐>>
1、CompositeUI-CreateBuilder
2、腾讯新浪通过IP地址获取当前地理位置(省份)的接口
3、jsp-简单的猜数小游戏
4、【转】C# 中 强制退出WinForm程序
5、ftp的安全问题


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn