Substructure of the tree (vs subtree)

Topic: Enter two binary trees A and B to determine whether B is a substructure of A. (Ps: we agree that the empty tree is not a substructure of any tree)

Note: The substructure is a part of the tree, not necessarily the subtree.

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    bool judge(TreeNode* pRoot1, TreeNode* pRoot2){
        if(pRoot1 == NULL && pRoot2 == NULL) return true;
        if(pRoot1 == NULL) return false;
        if(pRoot2 == NULL) return true;
        if(pRoot1 -> val != pRoot2 -> val) return false;
        return judge(pRoot1 -> left, pRoot2 -> left) && judge(pRoot1 -> right, pRoot2 -> right);
    }
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if(pRoot1 == NULL) return false;
        if(pRoot2 == NULL) return false;
        if(pRoot1 -> val == pRoot2 -> val){
            if(judge(pRoot1, pRoot2)) return true;
        }
        return HasSubtree(pRoot1 -> left, pRoot2) || HasSubtree(pRoot1 -> right, pRoot2);
    }
};

Topic: Determine whether B is a subtree of A.

class Solution {
public:
    bool judge(TreeNode* pRoot1, TreeNode* pRoot2){
        if(pRoot1 == NULL && pRoot2 == NULL) return true;
        if(pRoot1 == NULL) return false;
        if(pRoot2 == NULL) return false;
        if(pRoot1 -> val != pRoot2 -> val) return false;
        return judge(pRoot1 -> left, pRoot2 -> left) && judge(pRoot1 -> right, pRoot2 -> right);
    }
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if(pRoot1 == NULL) return false;
        if(pRoot2 == NULL) return false;
        if(pRoot1 -> val == pRoot2 -> val){
            if(judge(pRoot1, pRoot2)) return true;
        }
        return HasSubtree(pRoot1 -> left, pRoot2) || HasSubtree(pRoot1 -> right, pRoot2);
    }
};

  

Guess you like

Origin www.cnblogs.com/tyty-Somnuspoppy/p/12713893.html