请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
限制:
0 <= 节点个数 <= 1000
题源链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return root == NULL? true:recur(root->left, root->right);
}
private:
bool recur(TreeNode *left_root, TreeNode *right_root){
if (left_root == NULL && right_root == NULL){
// 左右子树同时为空
return true;
}
if (left_root == NULL || right_root == NULL
|| left_root->val != right_root->val){
// 左右子树的值不相等
return false;
}
return recur(left_root->left, right_root->right) &&
recur(left_root->right, right_root->left);
}
};