首页 > 其他 > 详细

leetcode:Symmetric Tree

时间:2015-04-05 09:03:50      阅读:248      评论:0      收藏:0      [点我收藏+]

非递归算法:

/**
 * 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 checkList(vector<int> list)
    {
        int n = list.size();
        for(int i=0;i<n;i++)
        {
            if(list[i]!=list[n-i-1])
                return false;
        }
        return true;
    }
    bool isSymmetric(TreeNode *root) {
        if(!root)
            return true;
        queue<pair<TreeNode*,int>> Q;
        vector<int> list;
        int pre = 0;
        Q.push(pair<TreeNode*,int>(root,1));
        while(!Q.empty())
        {
            pair<TreeNode *,int> p = Q.front();
            Q.pop();
            if(p.second!=pre)
            {
                if(checkList(list)==false)
                    return false;
                list.clear();
            }
            if(p.first==NULL)
                list.push_back(-1);
            else
                list.push_back(p.first->val);
            pre = p.second;
            if(p.first!=NULL)
            {
                if(p.first->left)
                    Q.push(pair<TreeNode*,int>(p.first->left,(p.second+1)));
                else
                    Q.push(pair<TreeNode*,int>(NULL,(p.second+1)));
                if(p.first->right)
                    Q.push(pair<TreeNode*,int>(p.first->right,(p.second+1)));
                else
                    Q.push(pair<TreeNode*,int>(NULL,(p.second+1)));
            }
        }
        return true;
    }
};

递归算法:

/**
 * 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 check(TreeNode *left,TreeNode *right)
    {
        if(!left&&!right)
            return true;
        if((left&&!right)||(!left&&right)||(left->val!=right->val))
            return false;
        return (check(left->left,right->right)&&check(left->right,right->left));
    }
    bool isSymmetric(TreeNode *root) {
        if(!root||(!root->left&&!root->right))
            return true;
        return check(root->left,root->right);
    }
};

leetcode:Symmetric Tree

原文:http://blog.csdn.net/majing19921103/article/details/44880529

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