/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2){ if(pRoot1 == NULL && pRoot2!=NULL )return false; if(pRoot2 == NULL)return true; //B没有了 存在子树 if(pRoot1->val == pRoot2->val){ return isSubtree(pRoot1->left, pRoot2->left) && isSubtree(pRoot1->right, pRoot2->right) ; }else return false ; } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { if(pRoot1==NULL || pRoot2==NULL)return false ; //先判断当前 再判A断子树 B始终拿头开始比 return isSubtree(pRoot1,pRoot2) || HasSubtree(pRoot1->left,pRoot2) || HasSubtree(pRoot1->right,pRoot2) ; } };
原文:https://www.cnblogs.com/Stephen-Jixing/p/13124979.html