輸入兩棵二叉樹A,B,判斷B是不是A的子結構。(ps:我們約定空樹不是任意一個樹的子結構)
python
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
result=False
if pRoot1 and pRoot2:
if pRoot1.val==pRoot2.val: #先找到根節點
result=self.DoesTreeHaveTree(pRoot1,pRoot2)
if not result:
result=self.HasSubtree(pRoot1.left,pRoot2)
if not result:
result=self.HasSubtree(pRoot1.right,pRoot2)
return result
def DoesTreeHaveTree(self,pRoot1,pRoot2):
if pRoot2==None:
return True
if pRoot1==None:
return False
if pRoot1.val != pRoot2.val:
return False
return self.DoesTreeHaveTree(pRoot1.left,pRoot2.left) and \
self.DoesTreeHaveTree(pRoot1.right,pRoot2.right)
c++
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
bool result = false;
if (pRoot1 != nullptr && pRoot2 != nullptr)
{
if (pRoot1->val==pRoot2->val)
result = DoesTreeHaveTree2(pRoot1, pRoot2);
if (!result)
result = HasSubtree(pRoot1->left, pRoot2);
if (!result)
result = HasSubtree(pRoot1->right, pRoot2);
}
return result;
}
bool DoesTreeHaveTree2(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (pRoot2 == nullptr)
return true;
if (pRoot1 == nullptr)
return false;
if (!(pRoot1->val == pRoot2->val))
return false;
return DoesTreeHaveTree2(pRoot1->left, pRoot2->left) && DoesTreeHaveTree2(pRoot1->right, pRoot2->right);
}
};