对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
/**
* 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 compare(TreeNode* left,TreeNode* right)
{
if(left == NULL && right != NULL)//左空 右不空
return false;
else if(left != NULL && right == NULL)//左不空 右空
return false;
else if(left == NULL && right == NULL)
return true;
else if(left->val != right->val)
return false;
bool outside = compare(left->left,right->right);//左子树的左边和右子树的右边
bool inside = compare(left->right,right->left);//左子树的右边和右子树的左边
bool isSame = outside && inside;
return isSame;
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return false;
return compare(root->left,root->right);
}
};