请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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
解题思路
既然是关于镜像对称,那么求出对称树,两者的结果应当是相同的。
代码展示
/**
* 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) {
if(!root)return true;
return judge(root,mirrorTree(root)); //原树和镜像树结果理论相同
}
TreeNode* mirrorTree(TreeNode* root) { //找出镜像树
if(!root)return NULL;
TreeNode* Root = new TreeNode(root->val);
Root->left = mirrorTree(root->right);
Root->right = mirrorTree(root->left);
return Root;
}
bool judge(TreeNode* A,TreeNode* B)
{
if(!A && !B)return true;
if(!A || !B)return false;
if(A->val!=B->val)return false;
return judge(A->left,B->left)&&judge(A->right,B->right);
}
};