Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2 / / 3 4 4 3
But the following is not:
1
/
2 2
3 3
根开始,如果根节点的左右不对称,则false,否则,看根节点的左右子树是否对称。
代码:(AC)
/** * 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 left_right_Symmetric(TreeNode* pleft,TreeNode* pright) { if(pleft==NULL&&pright==NULL) return true; if(pleft==NULL&&pright!=NULL)return false; if(pleft!=NULL&&pright==NULL)return false; if(pleft->val!=pright->val) return false; return left_right_Symmetric(pleft->left,pright->right)&&left_right_Symmetric(pleft->right,pright->left); } public: bool isSymmetric(TreeNode* root) { if(root == NULL) return true; if(root->left!=NULL&&root->right==NULL) return false; if(root->left==NULL&&root->right!=NULL) return false; if(root->left!=NULL&&root->right!=NULL&&root->left->val!=root->right->val)return false; else return left_right_Symmetric(root->left,root->right); } };
错误代码:没有理解对称树的概念。(WA)
/** * 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==NULL) return true; if(root->left==NULL&&root->right!=NULL) return false; else if(root->left!=NULL&&root->right==NULL)return false; else if(root->left==NULL&&root->right==NULL) return true; else if(root->left!=NULL&&root->right!=NULL&&root->left->val!=root->right->val) return false; else if(root->left!=NULL&&root->right!=NULL&&root->left->val==root->right->val) return isSymmetric(root->left)&&isSymmetric(root->right); } };