101. 对称二叉树 - 力扣(LeetCode)(点击前面链接即可查看题目)
一、题目
给你一个二叉树的根节点
root
, 检查它是否轴对称。示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false提示:
- 树中节点数目在范围
[1, 1000]
内-100 <= Node.val <= 100
二、解决思路以及代码
首先先看是不是空树,空树也是对称的返回true,然后他才有子树q,p,q,p都为空返回true,两个有一个为空一个不为空,返回fasle,两个子树的根(q,p)不相等。返回false,此时到这个两个根(q,p)都相同,要看他们的左右子树是不是继续相等,所以一个传q->left和->right
另一个传q->right和p->left
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool BTreeisSymmetric(struct TreeNode* root1, struct TreeNode* root2)
{
if(NULL == root1 && NULL == root2)
return true;
if(NULL == root1 || NULL == root2)
return false;
if(root1->val != root2->val)
return false;
return BTreeisSymmetric(root1->left, root2->right)
&& BTreeisSymmetric(root1->right, root2->left);
}
bool isSymmetric(struct TreeNode* root)
{
if(NULL == root)
return true;
return BTreeisSymmetric(root->left,root->right);
}