1. 程式人生 > >判斷二叉樹是否為映象對稱

判斷二叉樹是否為映象對稱

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;
    queue<TreeNode*>q;
    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; }