Language: C language
Idea: First judge the special case> then compare each node in turn> The two numbers are completely overlapped in the comparison, that is, the same tree.
As shown in the figure, if each step of the judgment is exactly the same (I did not finish the steps in the figure), the two trees are the same tree at this time.
If the two trees are not the same, as shown in the figure below, step ② will be Judge false
In general, the idea of this question is summarized as: synchronization,
look at the code
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p==NULL && q==NULL)
{
return true;
}
if(p==NULL || q==NULL)
{
return false;
}
if(p->val != q->val)
{
return false;
}
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
The submission result beats 100% of users