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 isSameTree(TreeNode* p, TreeNode* q) {
//if both trees are empty
if(!p && !q)
return true;
//if one of the tree is empty
else if(!p || !q)
return false;
TreeNode *ptr_p,*ptr_q;
queue<TreeNode* > q1,q2;
q1.push(p);
q2.push(q);
//loop until atleast one of the tree is fully traversed
while(!q1.empty() && !q2.empty())
{
ptr_p=q1.front();
ptr_q=q2.front();
//
if(ptr_p->val != ptr_q->val)
return false;
if(ptr_p->left && ptr_q->left)
{
q1.push(ptr_p->left);
q2.push(ptr_q->left);
}
else if(ptr_p->left || ptr_q->left)
{
return false;
}
if(ptr_p->right && ptr_q->right)
{
q1.push(ptr_p->right);
q2.push(ptr_q->right);
}
else if(ptr_p->right || ptr_q->right)
{
return false;
}
q1.pop();
q2.pop();
}
//if one of the tree is not fully traversed
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