题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
中左右序列化和中右左序列化,若相等返回true,否则返回false;
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
string left=beforeserialize(pRoot);
string right=afterserialize(pRoot);
if(left==right)
return true;
return false;
}
string beforeserialize(TreeNode* root)
{
string res{};
if(root==NULL)
{
res+="#!";
return res;
}
res+=(to_string(root->val)+"!");
res+=(beforeserialize(root->left)+"!");
res+=(beforeserialize(root->right)+"!");
return res;
}
string afterserialize(TreeNode* root)
{
string res{};
if(root==NULL)
{
res+="#!";
return res;
}
res+=(to_string(root->val)+"!");
res+=(afterserialize(root->right)+"!");
res+=(afterserialize(root->left)+"!");
return res;
}
};