Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
分析:
题目的要求是判断是否为对称树(镜像树),首先空树是对称树,其次若要镜像则必须满足左子树的右孩子和右子树的左孩子相等,左子树的右孩子和右子树的右孩子相等,注意是值相等,一直判断都都为空才终止,若中间层某个节点不符合,则必须终止,因为已经不符合,符合继续判断,直到所有符合
实现:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool _isSymmetric(TreeNode* left, TreeNode* right)
{
if (left == NULL && right == NULL)
return true;
if (left == NULL || right == NULL)//若仅仅有一方为空 则必然不是对称树
return false;
if (left->val != right->val)//注意这里是值
return false;
return _isSymmetric(left->right, right->left) && _isSymmetric(left->left, right->right);
}
bool isSymmetric(TreeNode* root) {
if (root == NULL)
{
return true;
}
return _isSymmetric(root->left,root->right);
}
};