Binary tree OJ question three

Hello friends, I haven’t updated my blog for a while. Mainly because I have to prepare for the school’s final exam during this period, so I didn’t allocate part of my time to the blog. Today we will continue to look at OJ related to binary tree recursion. question, what we are going to learn today is to judge the same trees, try to answer the question--100, direct link https://leetcode.cn/problems/same-tree/

Let’s first look at the question requirements of this question. We are given the root nodes p and q of two trees. Let us judge whether the two trees are the same. It is nothing more than judging whether the corresponding root nodes of the two trees are equal. Then we can start. Do the questions. First of all, we must first determine the situation when two trees are empty at the same time, then return true, that is,

if(p==NULL&&q==NULL)//两棵树同时为空
    {
        return true;
    }

The case where both trees are empty has been judged. What about the case where one tree is empty and the other is not empty? , it’s still the same routine, that is

 if(p==NULL||q==NULL)//只有一颗树为空
    {
        return false;
    }

Do you understand why it is written like this? The premise that the code can enter this if is that the two trees cannot be empty at the same time, so we can use || to judge whether one tree is empty. If p==NULL, it will not judge that the subsequent q==NULL is. If p!=NULL, it will be judged that q==NULL. As long as one of the two conditions is met, the two trees will not be equal and false will be returned.

It is determined that the tree is empty. If the code continues to go down, it means that the tree is not empty. Then it is directly judged whether the val of p and q are equal, that is,

if(p->val!=q->val)//判断p和q的val
    {
        return false;
    }

If the vals of p and q are not equal, then the two trees are destined to be different. There is no need to continue going down, and false can be returned directly.

Going further down, it is proved that p and q are equal as the root nodes of the two trees. We can recursively judge the left subtree and right subtree of the two trees, that is

return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);//递归判断左右子树

The code is finished here, we run the submission

 Complete code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
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);
}

Guess you like

Origin blog.csdn.net/weixin_67131528/article/details/134834723