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
Note:
Bonus points if you could solve it both recursively and iteratively.
递归判断左子树的左子树是否等于右子树的右子树和左子树的右子树是否等于右子树的左子树,代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
bool issysmetric(TreeNode *left,TreeNode *right)
{
if(!left&&!right) return true;
if(left && right && left->val==right->val) return issysmetric(left->left,right->right)&issysmetric(left->right,right->left);
else return false;
}
public:
bool isSymmetric(TreeNode *root) {
if(!root) return true;
return issysmetric(root->left,root->right);
}
};