【LeetCode】101. Symmetric Tree (2 solutions)

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / 
  2   2
 /  / 
3  4 4  3

But the following is not:

    1
   / 
  2   2
      
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

不管是递归还是非递归,找到关系就好做。

所谓对称,也就是:

1、left对应right

2、left->left对应right->right

3、left->right对应right->left

解法一:递归

/**
 * 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 isSymmetric(TreeNode *root) {
        if(!root)
            return true;
            
        return isSymTree(root->left, root->right);
    }
    bool isSymTree(TreeNode* p, TreeNode* q)
    {
        if(!isSameNode(p, q))
            return false;
        if(!p && !q)
            return true;
        return isSymTree(p->left, q->right) && isSymTree(p->right, q->left);
    }
    bool isSameNode(TreeNode* p, TreeNode* q)
    {
        if(!p && !q)
            return true;
        if((!p && q) || (p && !q) || (p->val != q->val))
            return false;
        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 isSymmetric(TreeNode *root) {
        if(!root)
            return true;
            
        if(!isSameNode(root->left, root->right))
            return false;
        if(!root->left && !root->right)
            return true;
            
        queue<TreeNode*> lqueue;
        queue<TreeNode*> rqueue;
        lqueue.push(root->left);
        rqueue.push(root->right);
        while(!lqueue.empty() && !rqueue.empty())
        {
            TreeNode* lfront = lqueue.front();
            TreeNode* rfront = rqueue.front();
            lqueue.pop();
            rqueue.pop();
            
            if(!isSameNode(lfront->left, rfront->right))
                return false;
            if(lfront->left && rfront->right)
            {
                lqueue.push(lfront->left);
                rqueue.push(rfront->right);
            }
            
            if(!isSameNode(lfront->right, rfront->left))
                return false;
            if(lfront->right && rfront->left)
            {
                lqueue.push(lfront->right);
                rqueue.push(rfront->left);
            }
        }
        return true;
    }
    bool isSameNode(TreeNode* p, TreeNode* q)
    {
        if(!p && !q)
            return true;
        if((!p && q) || (p && !q) || (p->val != q->val))
            return false;
        return true;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4134842.html