设置dfs的helper函数,定义为如果当前节点值相同,linklist的下一个节点和tree的left节点或者right节点继续相同,则当linklist的节点比较完成,说明满足条件。反之,走完tree某个路径上的节点依然找不到,则说明这条路径上没有满足条件的。外层的函数比较linkedlist的头节点和tree的根节点或者根节点的左子或者右子节点。
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
if not root:return False
if not head:return True
def dfs(head, root):
if not head:return True
if not root:return False
if head.val == root.val and (dfs(head.next, root.left) or dfs(head.next, root.right)):
return True
return False
if dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right):
return True
return False