题目链接
https://leetcode-cn.com/problems/symmetric-tree/
一、题目
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
二、分析和代码
1.分析
依旧是递归来解决
2.代码
代码如下(示例):
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSymmetric(struct TreeNode* root){
if (root == NULL) return true;
return compare(root->left, root->right);
}
int compare(struct TreeNode* l_root, struct TreeNode* r_root)
{
if (l_root == NULL && r_root == NULL) return true;//都为空
else if (l_root == NULL || r_root == NULL) return false;//其中一个为空
else if(l_root->val!= r_root->val) return false;
else
return compare(l_root->left, r_root->right) &&compare(l_root->right, r_root->left);
}