Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
- * solution1: recursion
- ```python3
- # -*- coding:utf-8 -*-
- # class TreeNode:
- # def __init__(self, x):
- # self.val = x
- # self.left = None
- # self.right = None
- class Solution:
- def HasSubtree(self, pRoot1, pRoot2):
- # write code here
- result = False
- if pRoot1 and pRoot2:
- if pRoo1.val == pRoot2.val:
- result = self.isSubtree(pRoot1,pRoot2)
- if not result:
- result = self.HasSubtree(pRoot1.left,pRoot2)
- if not result:
- result = self.HasSubtree(pRoot1.right,pRoot2)
- return result
- def isSubtree(self,root1,root2):
- if not root2:
- return True
- if not root1:
- return False
- if root1.val != root2.val:
- return False
- return self.isSubtree(root1.left,root2.left) and self.isSubtree(root1.right,root2.right)
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement