"Leetcode" 100. The same tree

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.
Insert picture description here
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.
Insert picture description here
If the two trees are not the same, as shown in the figure below, step ② will be Judge false

Insert picture description here
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

Guess you like

Origin blog.csdn.net/NanlinW/article/details/96870113
Recommended