LeetCode领扣 #101 对称二叉树(Symmetric Tree)

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

思路:提示递归和迭代了。。。我就按我的思路写了一下,没想到真过了。对称的二叉树,主要是:左子树的左结点要和右子树的右节点配对,左子树的右结点要和右子树的左节点配对(2个都是NULL也算)。需要注意的是,空树也是对称的。(结果是此算法胜过99.97%的cpp)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool cmp(TreeNode* rl, TreeNode* rr)
    {
        if( !rl && !rr )
            return true;
        else if( (rl&&!rr) || (!rl&&rr) || (rl->val!=rr->val) )
            return false;
        else
            return cmp(rl->left, rr->right) && cmp(rl->right, rr->left);  
    }

    bool isSymmetric(TreeNode* root) 
    {
        if( root == nullptr ) 
            return true;
        else	
            return cmp(root->left, root->right);				    
    }
};

猜你喜欢

转载自blog.csdn.net/Love_Irelia97/article/details/82872060