Niuke.com's sword refers to Offer - the substructure of the tree

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)


Problem solving ideas

To find out whether there is a subtree with the same structure as tree B in tree A, we can divide it into two steps:
  Step1: Find node R in tree A with the same value as the root node of B
  ; Does the subtree whose root node R contains the same structure as tree B?

When a node R with the same value as the root node of B is found in tree A, skip to step 2 to determine whether the subtree with R as the root node in tree A contains the same structure as tree B, if it is the same, then There are subtrees in tree A that have the same structure as tree B; if they are not the same, return to step1, continue to traverse the subtrees of R, and find the next node with the same value as the root node of B.

1. Find a node R in tree A that has the same value as the root node of B

It is necessary to use the idea of ​​recursion. First, determine whether the value of the current node and the root node of B are the same. If they are the same, then enter step2; .

2. Determine whether the subtree with R as the root node in tree A contains the same structure as tree B

If the value of the R node is different from the value of the node in the tree B, it is not a substructure; if it is the same, recursively determine whether their respective left and right children are the same.

The termination condition of the recursion is to reach the leaf node of tree A or tree B.

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)
    {
        if( pRoot2 == NULL || pRoot1 == NULL )
            return false;

        if( pRoot1->val == pRoot2->val )
            if( isSame(pRoot1,pRoot2) )
                return true;
        if ( HasSubtree(pRoot1->left,pRoot2) )
            return true;
        if ( HasSubtree(pRoot1->right,pRoot2) )
            return true;

        return false;
    }

    bool isSame(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if( pRoot2 == NULL )
            return true;
        if( pRoot1 == NULL )
            return false;
        if( pRoot1->val != pRoot2->val )
            return false;

        return isSame( pRoot1->left,pRoot2->left ) && isSame(pRoot1->right, pRoot2->right);
    }
};

Guess you like

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