28. 对称的二叉树

1. 描述

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

2. 例子

示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false

3. 限制

  • 0 <= 节点个数 <= 1000

4. 题解

n 是 i_root 中的节点数
时间复杂度: O(n)
空间复杂度: O(n)

class Solution 
{
private:
    bool isTreesEqual(TreeNode *i_root1, TreeNode *i_root2)
    {
        if(!i_root1 && !i_root2) return true;
        if(!i_root1 || !i_root2) return false;

        return i_root1->val == i_root2->val
            && isTreesEqual(i_root1->left, i_root2->right)
            && isTreesEqual(i_root1->right, i_root2->left)
            ;
    }
public:
    // bool isSymmetric(TreeNode* root)
    bool isSymmetric(TreeNode *i_root) 
    {
        return isTreesEqual(i_root, i_root);
    }
};
Last updated:
Tags:
comments powered by Disqus