递归做法:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if(root==NULL) return true;
if(root->left==NULL&&root->right!=NULL) return false;
if(root->left!=NULL&&root->right==NULL) return false;
return checkSymmetric(root->left,root->right);
}
bool checkSymmetric(TreeNode* node1,TreeNode* node2){
if(node1==NULL&&node2==NULL){
return true;
}
if(node1==NULL||node2==NULL) return false;
bool check1=checkSymmetric(node1->left,node2->right);
bool check2=checkSymmetric(node1->right,node2->left);
return node1->val==node2->val&&check1&&check2;
}
};
网上的迭代方法,可以AC ,:
- if(root==NULL)return true;
- queue<TreeNode*> lt,rt; //两个都用队列?是的,右边 用栈的话会出现问题
- if(root->left) lt.push(root->left);
- if(root->right) rt.push(root->right);
- TreeNode* l;
- TreeNode* r;
- while(!lt.empty() && !rt.empty())
- {
- l = lt.front();lt.pop();
- r = rt.front();rt.pop();
- if(l == NULL && r == NULL) continue;
- if(l == NULL || r == NULL) return false;
- if(l->val != r->val) return false;
- lt.push(l->left);
- lt.push(l->right);
- rt.push(r->right);
- rt.push(r->left); //左右子树的左子右子入队顺序相反,但是这样就能对应比较了?
- }
- if(lt.empty() && rt.empty())
- return true;
- else
- return false;
- }
- 我的非递归方法,注意右子不能采用栈,会出问题,似乎也是广搜的方法:
- /**
- * Definition for binary tree
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- class Solution {
- public:
- bool isSymmetric(TreeNode *root) {
- int num1=1,num2=0;
- TreeNode* cur1=NULL;
- TreeNode* cur2=NULL;
- queue<TreeNode*> stk1;
- queue<TreeNode*> stk2;
- if(root==NULL) return true;
- if(root->left==NULL&&root->right==NULL) return true;
- if((root->left==NULL&&root->right!=NULL)||(root->left!=NULL&&root->right==NULL)) return false;
- stk1.push(root->left);
- stk2.push(root->right);
- while(stk1.empty()!=true&&stk2.empty()!=true){
- for(int i=0;i<num1;i++){
- cur1=stk1.front();
- cur2=stk2.front();
- if(cur1->val!=cur2->val) return false;
- if((cur1->left==NULL&&cur2->right!=NULL)||(cur1->left!=NULL&&cur2->right==NULL)||(cur1->right==NULL&&cur2->left!=NULL)||(cur1->right!=NULL&&cur2->left==NULL)) return false;
- if(cur1->left!=NULL){
- stk1.push(cur1->left);
- cur1->left=NULL;
- num2++;
- }
- if(cur1->right!=NULL){
- stk1.push(cur1->right);
- cur1->right=NULL;
- num2++;
- }
- if(cur2->right!=NULL){
- stk2.push(cur2->right);
- cur2->right=NULL;
- }
- if(cur2->left!=NULL){
- stk2.push(cur2->left);
- cur2->left=NULL;
- }
- stk1.pop();
- stk2.pop();
- }
- num1=num2;
- num2=0;
- }
- if(stk1.empty()!=true||stk2.empty()!=true){
- return false;
- }
- return true;
- }
- };