题目描述
思路分析
递归
写一个递归函数
f
f
f:来判断两棵树是否是镜像关系。并且我们知道,一棵树是镜像树等价于一棵树的镜像是自身,也即
f
(
r
o
o
t
,
r
o
o
t
)
=
=
t
r
u
e
f(root,root)==true
f(root,root)==true;
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool f(TreeNode* p,TreeNode* q){
if(p&&!q||!p&&q) return false;
if(!p&&!q) return true;
return p->val==q->val&&f(p->left,q->right)&&f(p->right,q->left);
}
bool isSymmetric(TreeNode* root) {
return f(root,root);
}
};