Niuke.com Brush Questions | Substructure of Trees

Topic source: Niuke.com
programming link

Topic description:

Input two binary trees A and B, and determine whether B is a substructure of A. (ps: we agree that an empty tree is not a substructure of any tree)

Parse:

The whole process can be imagined: 1. A and B first check whether the root node is right, and if so, check whether the left and right nodes of the root node are right.
2. If the first root node is not paired successfully, replace it with the left child node of A for pairing.
3. If the left child node is unsuccessful, replace it with the right child node of A for pairing.

Code:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        bool result = false;
        if(pRoot1 !=NULL && pRoot2 !=NULL)
        {
            if(pRoot1->val == pRoot2->val)  //如果根结点配对了,则直接继续
            {
                result = HasSubTree2(pRoot1,pRoot2);
            }
            if(!result)
            {
                result = HasSubtree(pRoot1->left,pRoot2);
            }
            if(!result)
            {
                result = HasSubtree(pRoot1->right,pRoot2);
            }
        }        
        return result;
    }

    bool HasSubTree2(TreeNode* pRoot1,TreeNode* pRoot2)
    {
        if(pRoot2==NULL)
            return true;
        if(pRoot1 == NULL)
            return false;
        if(pRoot1->val != pRoot2->val)
            return false;
        return HasSubTree2(pRoot1->left,pRoot2->left) && HasSubTree2(pRoot1->right,pRoot2->right);       
    }
};

Running time: 3ms; Occupied memory: 480k

Someone else's code:
the same idea

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class Solution {
public:
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if (pRoot1 == nullptr || pRoot2 == nullptr)
            return false;   //直接返回错误
        return isTheSameTree(pRoot1, pRoot2) || 
            HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
    }
    bool isTheSameTree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if (pRoot2 == nullptr)
            return true;
        if (pRoot1 == nullptr && pRoot2 != nullptr)
            return false;
        return pRoot1->val == pRoot2->val && 
            isTheSameTree(pRoot1->left, pRoot2->left) && isTheSameTree(pRoot1->right, pRoot2->right);
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568122&siteId=291194637