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
递归:
/**
* 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 fun(TreeNode* left,TreeNode* right){
if(!left&&!right){
return true;
}
if(left&&right&&left->val==right->val){
return fun(left->left,right->right)&&fun(left->right,right->left);
}
return false;
}
bool isSymmetric(TreeNode* root) {
if(!root){
return true;
}
return fun(root->left,root->right);
}
};
非递归:
/**
* 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 isSymmetric(TreeNode* root) {
queue<TreeNode*>q1,q2;
TreeNode* head1;
TreeNode* head2;
q1.push(root);
q2.push(root);
while(!q1.empty()&&!q2.empty()){
head1=q1.front();
head2=q2.front();
q1.pop();
q2.pop();
if(!head1&&!head2){
continue;
}
if(!head1||!head2){
return false;
}
if(head1->val!=head2->val){
return false;
}
q1.push(head1->left);
q1.push(head1->right);
q2.push(head2->right);
q2.push(head2->left);
}
return true;
}
};