实则是 菜鸡一枚。。。先镜像,然后复制,然后比较 两树是否相等。。。代码贴上,去学习大佬的代码了
class Solution { public: bool isSymmetrical(TreeNode* pRoot) { TreeNode* mirroroot=treeCopy(pRoot); mirror(pRoot); return doesAandB(pRoot,mirroroot); } TreeNode *treeCopy(TreeNode* root) //复制二叉树 { if(root==NULL) return NULL; TreeNode *c=new TreeNode(root->val); c->left=treeCopy(root->left); c->right=treeCopy(root->right); return c; } void mirror(TreeNode* pRoot) //找二叉树的镜像 { if(pRoot==NULL) return ; if(pRoot->left!=NULL && pRoot->right!=NULL) { TreeNode *temp=pRoot->left; pRoot->left=pRoot->right; pRoot->right=temp; } else if(pRoot->left!=NULL && pRoot->right==NULL) { pRoot->right=pRoot->left; pRoot->left=NULL; } else if(pRoot->right!=NULL && pRoot->left==NULL) { pRoot->left=pRoot->right; pRoot->right=NULL; } else return ; mirror(pRoot->left); mirror(pRoot->right); } bool doesAandB(TreeNode* pRoot,TreeNode* mirrorRoot) //判断二叉树是否相等 { if(pRoot==NULL && mirrorRoot==NULL) return true; else if(pRoot==NULL && mirrorRoot!=NULL) return false; else if(pRoot!=NULL && mirrorRoot==NULL) return false; if(pRoot->val!=mirrorRoot->val) return false; return doesAandB(pRoot->left,mirrorRoot->left)&&doesAandB(pRoot->right,mirrorRoot->right); } };