给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
解决方案:
class Solution_101 {
//递归判断每一个对称位置节点的左子树的左节点是否等于右子树的右节点
bool judge(TreeNode* a, TreeNode* b){
if (!a && !b) return true;
if (!a && b || a && !b) return false;
if (a->val != b->val) return false;
return judge(a->left, b->right) && judge(a->right, b->left);
}
public:
bool isSymmetric(TreeNode* root) {
if (!root)
return false;
return judge(root->left, root->right);
}
};