Sub-structure and sub-structure of the tree
1. Question
Enter Two Binary Trees A and B to determine whether B is A sub-structure. The binary tree structure is as follows:
Struct BinaryTreeNode
{
Int m_nValue;
BinaryTreeNode * m_pLeft;
BinaryTreeNOde * m_pRight;
};
In example 1-1 (a), the red part and (B) have the same structure: the corresponding data fields are the same.
Figure 1-1 substructure
2. Analysis
Obviously, if the root node pRoot1 and pRoot2 of Tree B in tree A meet the following requirements, B is the sub-structure of:
(1) The values of pRoot1 and pRoot2 are the same;
(2) The left subtree of pRoot1 is exactly the same as that of pRoot2;
(3) The right subtree of pRoot1 is exactly the same as that of pRoot2.
3. Implementation Method
Method 1:
The result is obtained through recursive traversal tree. The time complexity O (m * n), where m and n are the number of nodes in A and B respectively.
Method 2:
(1) traverse tree A and B in order to get two traversal sequences: Apre and Bpre.
(2) The next traversal tree A and B get two traversal sequences: Apast and Bpast.
(3) Use the string comparison algorithm KMP for detection. If Apre contains Bpre and Apast contains Bpast, B is the sub-structure of A, and vice versa.
The time complexity O (m + n) of this method, where m and n are the number of nodes in A and B respectively.
Note: because a traversal order cannot uniquely determine a binary tree, two traversal sequences are required.
4. Code
In the Code, if the two operators are null, B is not the sub-structure of.
boolHasSubtree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2){ bool result = false; if(pRoot1 != NULL && pRoot2 !=NULL) { if(pRoot1->m_nValue ==pRoot2->m_nValue) result = DoesTree1HaveTree2(pRoot1,pRoot2); if(!result) result =HasSubtree(pRoot1->m_pLeft, pRoot2); if(!result) result = HasSubtree(pRoot1->m_pRight,pRoot2); } return result;} boolDoesTree1HaveTree2(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2){ if(pRoot2 == NULL) return true; if(pRoot1 == NULL) return false; if(pRoot1->m_nValue != pRoot2->m_nValue) return false; return DoesTree1HaveTree2(pRoot1->m_pLeft, pRoot2->m_pLeft) && DoesTree1HaveTree2(pRoot1->m_pRight,pRoot2->m_pRight);}