Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree
[1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following
[1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
做了这么多的题目,发觉树的问题都可以用递归解决,可是我一直没有勇气用非递归的方法解决树的问题,因为自己真的对堆栈不太熟悉。这道题也是递归,判断是否是对称树。
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 tree(TreeNode* left1,TreeNode* right1)
{
if(left1==NULL&&right1==NULL)
return true;
else if((left1!=NULL&&right1==NULL)||(left1==NULL&&right1!=NULL))
return false;
else if((left1!=NULL&&right1!=NULL)&&(left1->val!=right1->val))
return false;
else
return tree(left1->left,right1->right)&&tree(left1->right,right1->left);
}
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
else
return tree(root->left,root->right);
}
};