leetcode:Symmetric Tree

非遞歸算法:

/**
 * 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);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章