Title Description
Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)
Problem-solving ideas
Verify B is not A subtree, intuitive approach A traversing the tree in any order, once the child node and the root node B are the same, this will be the subtree rooted at the node B tree and comparison is satisfied lookup successful, otherwise lookup fails. Tree preorder traversal of the most intuitive, here to preorder, for example, gives C ++ implementation code:
/ * Struct the TreeNode { int Val; struct the TreeNode * left; struct the TreeNode * right; the TreeNode (int X): Val (X), left (NULL), right (NULL) { } }; * / class Solution { public : BOOL HasSubtree (* pRoot1 the TreeNode, the TreeNode * pRoot2) { BOOL isSub = false ; // appears a two arbitrary tree is empty, return false IF (pRoot1 pRoot2 = = NULL &&!! NULL) { IF (pRoot1-> Val pRoot2- ==> Val) { isSub =doesTree1HaveTree2(pRoot1,pRoot2); }if(!isSub){ isSub=HasSubtree(pRoot1->left,pRoot2); }if(!isSub){ isSub=HasSubtree(pRoot1->right,pRoot2); } } return isSub; } bool doesTree1HaveTree2(TreeNode* pRoot1, TreeNode* pRoot2){ if(pRoot2==NULL){ return true; } if(pRoot1==NULL){ return false; } if(pRoot1->val!=pRoot2->val){ return false; } return doesTree1HaveTree2(pRoot1->left,pRoot2->left) && doesTree1HaveTree2(pRoot1->right,pRoot2->right); } };