Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root->left && !root->right)
return true;
else if(!root->left || !root->right)
return false;
queue<TreeNode *> q1,q2;
TreeNode *p1,*p2;
q1.push(root->left);
q2.push(root->right);
while(!q1.empty() && !q2.empty())
{
p1=q1.front();
p2=q2.front();
if(p1->val!=p2->val)
return false;
if(p1->left && p2->right)
{
q1.push(p1->left);
q2.push(p2->right);
}
else if (p1->left || p2->right)
{
return false;
}
if(p2->left && p1->right)
{
q2.push(p2->left);
q1.push(p1->right);
}
else if (p2->left || p1->right)
{
return false;
}
q1.pop();
q2.pop();
}
if(!q1.empty() || !q2.empty())
return false;
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment