19. Subtree of Another Tree
Last updated
Last updated
4
/ \
1 2class Solution
{
public:
bool compare(TreeNode *head1, TreeNode *head2)
{
queue<TreeNode *> q1;
queue<TreeNode *> q2;
q1.push(head1);
q2.push(head2);
while (!q1.empty() && !q2.empty())
{
TreeNode *p = q1.front();
q1.pop();
TreeNode *q = q2.front();
q2.pop();
if (p->val != q->val)
{
return false;
}
if (p->left && !q->left || q->left && !p->left)
{
return false;
}
if (p->right && !q->right || q->right && !p->right)
{
return false;
}
if (p->left)
{
q1.push(p->left);
q2.push(q->left);
}
if (p->right)
{
q1.push(p->right);
q2.push(q->right);
}
}
return true;
}
bool isSubtree(TreeNode *s, TreeNode *t)
{
stack<TreeNode *> st;
while (!st.empty() || s != NULL)
{
if (s != NULL)
{
if (s->val == t->val)
{
if (compare(s, t))
{
return true;
}
}
st.push(s);
s = s->left;
}
else
{
s = st.top();
st.pop();
s = s->right;
}
}
return false;
}
};