|
| 1 | +# Time: O(n + l) |
| 2 | +# Space: O(h + l) |
| 3 | + |
| 4 | +# Definition for singly-linked list. |
| 5 | +class ListNode(object): |
| 6 | + def __init__(self, x): |
| 7 | + self.val = x |
| 8 | + self.next = None |
| 9 | + |
| 10 | + |
| 11 | +# Definition for a binary tree node. |
| 12 | +class TreeNode(object): |
| 13 | + def __init__(self, x): |
| 14 | + self.val = x |
| 15 | + self.left = None |
| 16 | + self.right = None |
| 17 | + |
| 18 | + |
| 19 | +# kmp solution |
| 20 | +class Solution(object): |
| 21 | + def isSubPath(self, head, root): |
| 22 | + """ |
| 23 | + :type head: ListNode |
| 24 | + :type root: TreeNode |
| 25 | + :rtype: bool |
| 26 | + """ |
| 27 | + def getPrefix(head): |
| 28 | + pattern, prefix = [head.val], [-1] |
| 29 | + j = -1 |
| 30 | + node = head.next |
| 31 | + while node: |
| 32 | + while j+1 and pattern[j+1] != node.val: |
| 33 | + j = prefix[j] |
| 34 | + if pattern[j+1] == node.val: |
| 35 | + j += 1 |
| 36 | + pattern.append(node.val) |
| 37 | + prefix.append(j) |
| 38 | + node = node.next |
| 39 | + return pattern, prefix |
| 40 | + |
| 41 | + def dfs(pattern, prefix, root, j): |
| 42 | + if not root: |
| 43 | + return False |
| 44 | + while j+1 and pattern[j+1] != root.val: |
| 45 | + j = prefix[j] |
| 46 | + if pattern[j+1] == root.val: |
| 47 | + j += 1 |
| 48 | + if j+1 == len(pattern): |
| 49 | + return True |
| 50 | + return dfs(pattern, prefix, root.left, j) or \ |
| 51 | + dfs(pattern, prefix, root.right, j) |
| 52 | + |
| 53 | + if not head: |
| 54 | + return True |
| 55 | + pattern, prefix = getPrefix(head) |
| 56 | + return dfs(pattern, prefix, root, -1) |
| 57 | + |
| 58 | + |
| 59 | +# Time: O(n * min(h, l)) |
| 60 | +# Space: O(h) |
| 61 | +# dfs solution |
| 62 | +class Solution2(object): |
| 63 | + def isSubPath(self, head, root): |
| 64 | + """ |
| 65 | + :type head: ListNode |
| 66 | + :type root: TreeNode |
| 67 | + :rtype: bool |
| 68 | + """ |
| 69 | + def dfs(head, root): |
| 70 | + if not head: |
| 71 | + return True |
| 72 | + if not root: |
| 73 | + return False |
| 74 | + return root.val == head.val and \ |
| 75 | + (dfs(head.next, root.left) or |
| 76 | + dfs(head.next, root.right)) |
| 77 | + |
| 78 | + if not head: |
| 79 | + return True |
| 80 | + if not root: |
| 81 | + return False |
| 82 | + return dfs(head, root) or \ |
| 83 | + self.isSubPath(head, root.left) or \ |
| 84 | + self.isSubPath(head, root.right) |
0 commit comments