给定一个二叉树,检查它是否是镜像对称的。
先创建一个镜像的二叉树,即交换二叉树的左右子树,然后比较二叉树的异同即可。
注意判断异同的时候origin和new都可能单独为nullptr,不要漏掉情况
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSymmetric(TreeNode* root) { 13 TreeNode* symmetricTree=build_symmetric(root); 14 return judge_same(root,symmetricTree); 15 } 16 17 bool judge_same(TreeNode* origin, TreeNode* symmetric){ 18 if(origin==nullptr) 19 return symmetric==nullptr; 20 if(symmetric==nullptr) 21 return false; 22 return origin->val==symmetric->val && judge_same(origin->left,symmetric->left) 23 && judge_same(origin->right,symmetric->right); 24 } 25 26 TreeNode* build_symmetric(TreeNode* root){ 27 if(root==nullptr) 28 return nullptr; 29 TreeNode* newTree=new TreeNode(root->val); 30 newTree->left=build_symmetric(root->right); 31 newTree->right=build_symmetric(root->left); 32 return newTree; 33 } 34 };