输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
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 { 14 if(!pRoot1||!pRoot2) 15 return false; 16 bool ans = false; 17 if(pRoot1->val == pRoot2->val)ans = is_subTree(pRoot1,pRoot2); 18 if(!ans) ans = HasSubtree(pRoot1->left,pRoot2); 19 if(!ans) ans = HasSubtree(pRoot1->right,pRoot2); 20 return ans; 21 } 22 bool is_subTree(TreeNode* pRoot1, TreeNode* pRoot2){ 23 if(!pRoot2)return true; 24 if(!pRoot1)return false; 25 bool ans = true; 26 if(pRoot1->val != pRoot2->val)ans = false; 27 if(ans) ans = is_subTree(pRoot1->left,pRoot2->left); 28 if(ans) ans = is_subTree(pRoot1->right,pRoot2->right); 29 return ans; 30 } 31 };