来源:力扣(LeetCode)题目:给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
题目不难,直接上代码:
/**
* 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 ismirror(TreeNode* p,TreeNode* q){
if(!p&&!q)
return true;
if(!p||!q)
return false;
if(p->val==q->val)
return ismirror(p->right,q->left)&&ismirror(p->left,q->right);
return false;
}
bool isSymmetric(TreeNode* root) {
return ismirror(root,root);
}
};