leetcode -symmetric tree

\\采用递归方法,挺好理解的

class
Solution { public: bool isSame(TreeNode *left,TreeNode *right){ if((right==NULL&&left!=NULL)||(left==NULL&&right!=NULL))return false; if(left==NULL&&right==NULL)return true; if(left->val!=right->val)return false; return isSame(left->right,right->left)&&isSame(left->left,right->right); } bool isSymmetric(TreeNode* root) { if(root==NULL)return true; return isSame(root->left,root->right); } };
\\法2:使用两个队列,入列的方式相反即可


class
Solution { public: bool isSymmetric(TreeNode* root) { if(root==NULL)return true; queue<TreeNode *> q1,q2; q1.push(root->left); q2.push(root->right); while(!q1.empty()&&!q2.empty()){ TreeNode *n1=q1.front(); TreeNode *n2=q2.front(); q1.pop(); q2.pop(); if((!n1&&n2)||(n1&&!n2))return false; if(n1&&n2){ if(n1->val!=n2->val)return false; q1.push(n1->left); q1.push(n1->right); q2.push(n2->right); q2.push(n2->left); } } return true; } };

猜你喜欢

转载自www.cnblogs.com/illfuckingkyzb/p/10171882.html