版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89310388
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.
题目大意:
判断给出的二叉树是否是对称的。
解题思路:
同时判读左右两边的值,在递归过程中应该是判断(cor->l,cor->r)&&(cor->r,cor->l)。
/**
* 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 {
private:
bool valid(TreeNode* l, TreeNode *r){
if(l == NULL && r == NULL){
return true;
}else if(l!=NULL && r !=NULL){
if(l->val==r->val){
return valid(l->left,r->right)&&valid(l->right, r->left);
}else{
return false;
}
}else{
return false;
}
}
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL){
return true;
}
return valid(root->left, root->right);
}
};