leetcode binary tree

Insert image description here

The following two questions are relatively similar, so we will discuss them together for a better understanding.

https://leetcode.cn/problems/same-tree/description/

Insert image description here
This question is to compare whether two trees are the same. In fact, it seems that this only needs to compare the current nodes. We analyze it into a sub-problem to determine whether the current nodes of the two trees are consistent. For example, the val of p and q is empty. When we do this, our code is actually written.

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);
}

So this question is relatively simple. To analyze it into sub-problems, you only need to look at the current sub-node. The next similar one is
https://leetcode.cn/ problems/univalued-binary-tree/description/

Insert image description here
The sub-problem that this question can be divided into is that we determine whether the parent node and the child node are the same sub-problem. However, one issue that still needs to be considered is the issue of empty, because if it is empty, it needs to return true. If it is empty, it is still true. It’s a joke, hahahaha, for example, when we have a node, the left and right children are empty, then we must output true at the end. With this analysis, we can write the code like this.

bool isUnivalTree(struct TreeNode* root) {
    
    
    if(root == NULL)
    {
    
    
        return true;
    }
    
    if(root->left != NULL && root->left->val != root->val)
    {
    
    
        return false;
    }
    if(root->right != NULL && root->right->val != root->val)
    {
    
    
        return false;
    }
    return isUnivalTree(root->left) && isUnivalTree(root->right);
}

I divided the three questions into two articles hahahaha, mainly for traffic support, but I promise that I don’t have any water articles. I have the final exam recently and I have to be busy.

Insert image description here

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/134701706