题目链接:101. 对称二叉树 - 力扣(LeetCode)
题目中说至少存在一个节点,所以我们只需要对比左右子树
写一个子函数对比左右子树:用递归的思路,左子树的左子树和右子树的右子树对比,左子树的右子树和右子树的左子树对比,我们只需要考虑几种情况:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool _isSymmetric(struct TreeNode*root1,struct TreeNode*root2)
{
if(root1==NULL&&root2==NULL)
return true;
if(root1==NULL||root2==NULL)
return false;
if(root1->val!=root2->val)
return false;
return _isSymmetric(root1->left,root2->right)&&_isSymmetric(root1->right,root2->left);
}
bool isSymmetric(struct TreeNode* root) {
return _isSymmetric(root->left,root->right);
}