判断二叉树是否为镜像对称

leetcode 101


思路:将左右两个对称的树元素分前后送入队列,判断时一次取两个进行判断

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

bool isSymmetric(TreeNode* root) {
    if(!root) return true;
    queueq;
    TreeNode*l,*r;
    q.push(root->right);
    q.push(root->left);
    while(!q.empty()) {
        r = q.front();
        q.pop();
        l = q.front();
        q.pop();
        if(!r && !l) continue;
        if(r && !l || !r && l) return false;
        if(r->val != l->val) return false;
        q.push(r->right);
        q.push(l->left);
        q.push(r->left);
        q.push(l->right);
    }
    return true;
}

你可能感兴趣的:(算法,C++)