Q: Input two binary trees A and B, and judge whether B is a substructure of A. (ps: we agree that an empty tree is not a substructure of any tree)
A: To find out whether there is a subtree in tree A with the same structure as tree B. We can divide it into two steps:
The first step is to find a node R with the same value as the root node of B in tree A,
The second step is to determine whether the subtree with R as the root node in tree A contains the same structure as tree B.
/* 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) { //After finding the same node, determine whether it contains the same structure result = isSubTree(pRoot1, pRoot2); } if (!result)//Find the same node in the left subtree { result = HasSubtree(pRoot1->left, pRoot2); } if (!result)//Find the same node in the right subtree { result = HasSubtree(pRoot1->right, pRoot2); } } return result; } bool isSubTree(TreeNode* pRoot1, TreeNode* pRoot2) { if(NULL == pRoot2) { return true; } if(NULL == pRoot1) { return false; } if(pRoot1->val != pRoot2->val) { return false; } return isSubTree(pRoot1->left, pRoot2->left) && isSubTree(pRoot1->right, pRoot2->right); } };