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
思路:基本上树的题就是迭代和遍历两种啦。
这道题一开始觉得有点难,因为root为空的时候应该返回true,但是如果迭代的话,当叶子节点变成root的时候应该返回false。也忘记考虑不仅结构要对称,而且值也要对称。
最后解决方案如下:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return 1;
return helper(root->left,root->right);
}
bool helper(TreeNode* left,TreeNode* right){
if(!left&&!right)return 1;
else if(!left||!right) return 0;
if(left->val!=right->val) return 0;
return helper(left->left,right->right)&&helper(left->right,right->left);
}
};