c_cpp 101.对称树

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 101.对称树相关的知识,希望对你有一定的参考价值。

//Runtime: 8 ms, faster than 39.55%

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return travelTree(root->left,root->right);
    }
    
    bool travelTree(TreeNode* p,TreeNode* q){
        if(!p && !q) 
            return true;
        else if(!p || !q)
            return false;
        if(p->val != q->val)
            return false;
        return travelTree(p->left,q->right) && travelTree(p->right,q->left);
    }
};
//Runtime: 8 ms, faster than 39.55%

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        TreeNode* t1, *t2;
        queue<TreeNode*> q;
        q.push(root);
        q.push(root);
        while(!q.empty()){
            t1 = q.front();
            q.pop();
            t2 = q.front();
            q.pop();
            if(t1 == NULL && t2 == NULL)
                continue;
            if(t1 == NULL || t2 == NULL)
                return false;
            if(t1->val != t2->val)
                return false;
            q.push(t1->left);
            q.push(t2->right);
            q.push(t1->right);
            q.push(t2->left);
        }
        return true;
    }
};

以上是关于c_cpp 101.对称树的主要内容,如果未能解决你的问题,请参考以下文章

java 101.对称树(#1 Recursive).java

java 101.对称树(#1 Recursive).java

java 101.对称树(#1 Recursive).java

java 101.对称树(#1 Recursive).java

java 101.对称树(#1 Recursive).java

java 101.对称树(#1 Recursive).java