1.题目:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
2.代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//树对称即两个子树是镜像
bool isMirror(struct TreeNode* p,struct TreeNode* q){
if(!p&&!q) //都不存在
return true;
if(!p||!q) //有一个不存在
return false;
if(p->val==q->val) //都存在且相等
return isMirror(p->left,q->right)&&isMirror(p->right,q->left);
return false;
}
bool isSymmetric(struct TreeNode* root) {
return isMirror(root,root); // []情况
}
3.知识点:
树的递归。