Programmer interview golden classic-interview questions 04.10. Check the subtree

1. Topic introduction

Check the subtree. You have two very large binary trees: T1, with tens of thousands of nodes; T2, with tens of thousands of nodes. Design an algorithm to determine whether T2 is a subtree of T1.

If T1 has such a node n and its subtree is exactly the same as T2, then T2 is the subtree of T1, that is, if the tree is cut from node n, the tree obtained is exactly the same as T2.

Example 1:

 Input: t1 = [1, 2, 3], t2 = [2]
 Output: true
Example 2:

 Input: t1 = [1, null, 2, 4], t2 = [3, 2]
 Output: false
Prompt:

The range of tree nodes is [0, 20000].

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/check-subtree-lcci The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       This question is divided into the following situations:

(1) When t2 is NULL, then t2 is a subtree of any tree.

(2) When t1 is NULL and t2 is not empty, t2 is not a subtree of t1.

(3) When both t1 and t2 are not empty, and t1 != t2, look for nodes with the same value as t2 in the left and right subtrees of t1. (Recursively)

(4) When the values ​​of t1 and t2 are equal, the values ​​of all child nodes of t1 and t2 are all equal, so that the condition that t2 is a subtree of t1 can be satisfied.

Three, problem-solving code

class Solution {
private:
    bool isFirst = true;
public:
    bool checkSubTree(TreeNode* t1, TreeNode* t2) {
        if(t2 == NULL) return true;
        if(t1 == NULL) return false;
        return dfs(t1, t2);
    }

    bool dfs(TreeNode* t1, TreeNode* t2)
    {
        if(t2 == NULL && t1 == NULL)
        {
            return true;
        }
        else if(t2 == NULL || t1 == NULL)
            return false;
        if(t1->val != t2->val)
            return dfs(t1->left, t2) || dfs(t1->right, t2);
        else
            return dfs(t1->left, t2->left) && dfs(t1->right, t2->right);
    }

};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108140350