输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
C++:
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 };*/ 10 class Solution { 11 public: 12 bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2){ 13 bool result = false ; 14 if (pRoot1 != NULL && pRoot2 != NULL){ 15 if (pRoot1->val == pRoot2->val) 16 result = isSubtree(pRoot1 , pRoot2) ; 17 if (!result) 18 result = HasSubtree(pRoot1->left , pRoot2) ; 19 if (!result) 20 result = HasSubtree(pRoot1->right , pRoot2) ; 21 } 22 return result ; 23 } 24 25 bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2){ 26 if (pRoot2 == NULL) 27 return true ; 28 if (pRoot1 == NULL) 29 return false ; 30 if (pRoot1->val != pRoot2->val) 31 return false ; 32 return isSubtree(pRoot1->left , pRoot2->left) && isSubtree(pRoot1->right , pRoot2->right) ; 33 } 34 };