题目
解题思路
-
面试题04.10 - 标准的检查子树问题:
遍历大的一颗树,一旦发现了和小树(待检测子树)根节点相同的结点,再来判断两者的左子树和右子树是否相等,可以发现这是一个递归的过程。 -
二叉树中的列表:
同样也是遍历树,一旦发现和链表头数值相同的结点,再来判断该树的下一层,其左右结点中是否有链表下一个结点数值,如果有,再判断子节点的子节点中是否有下下一个结点的数值,仍然是一个递归的过程。和标准子树问题不同,一旦找到可能的结点,只要其子节点中有一个满足数值的要求就可以继续判断下一层。
代码实现
- 二叉树中的列表
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
if not head:
return True
if not root:
return False
# 判断是否满足路径要求
def check(node, h):
if not h:
return True
if not node or node.val != h.val:
return False
# 左右结点中只要有一个满足链表值即可
return check(node.left, h.next) or check(node.right, h.next)
while root:
# 可能存在路径的点
if root.val == head.val:
if check(root.left, head.next) or check(root.right, head.next):
return True
# 继续再左右子树中找可能的结点
return self.isSubPath(head, root.left) or self.isSubPath(head, root.right)
面试题 04.10. 检查子树
class Solution:
def checkSubTree(self, t1: TreeNode, t2: TreeNode) -> bool:
if not t2:
return True
if not t1:
return False
# 找到可能的结点,判断两者子树是否完全相等
if t1.val == t2.val:
if self.checkSubTree(t1.left, t2.left) and self.checkSubTree(t1.right, t2.right):
return True
# 继续在左右子树中找可能的结点
return self.checkSubTree(t1.left, t2) or self.checkSubTree(t1.right, t2)