给定二叉树,返回它是否是自身的镜像(即这棵二叉树是否对称)。
样例
样例1
输入: {1,2,2,3,4,4,3}
输出: true
解释:
1
/ \
2 2
/ \ / \
3 4 4 3
{1,2,2,3,4,4,3}这棵二叉树是对称的
样例2
输入: {1,2,2,#,3,#,3}
输出: false
解释:
1
/ \
2 2
\ \
3 3
很显然这棵二叉树并不对称
挑战
用递归和迭代的方法来解决这个问题(2种解法)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: root of the given tree
* @return: whether it is a mirror of itself
*/
bool isSymmetric(TreeNode * root) {
// Write your code here
if(root==NULL) return true;
return recursion(root->left,root->right);
}
bool recursion(TreeNode*root1,TreeNode*root2)
{
if(root1==NULL&&root2==NULL) return true;
else if(root1==NULL||root2==NULL) return false;
else if(root1->val!=root2->val) return false;
return recursion(root1->left,root2->right)&&recursion(root1->right,root2->left);
}
};