-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.py
29 lines (28 loc) · 910 Bytes
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
def dfs(head, root):
if head is None:
return True
if root is None:
return False
if root.val != head.val:
return False
return dfs(head.next, root.left) or dfs(head.next, root.right)
if root is None:
return False
return (
dfs(head, root)
or self.isSubPath(head, root.left)
or self.isSubPath(head, root.right)
)