forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-list-in-binary-tree.py
84 lines (74 loc) · 2.23 KB
/
linked-list-in-binary-tree.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Time: O(n + l)
# Space: O(h + l)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# kmp solution
class Solution(object):
def isSubPath(self, head, root):
"""
:type head: ListNode
:type root: TreeNode
:rtype: bool
"""
def getPrefix(head):
pattern, prefix = [head.val], [-1]
j = -1
node = head.next
while node:
while j+1 and pattern[j+1] != node.val:
j = prefix[j]
if pattern[j+1] == node.val:
j += 1
pattern.append(node.val)
prefix.append(j)
node = node.next
return pattern, prefix
def dfs(pattern, prefix, root, j):
if not root:
return False
while j+1 and pattern[j+1] != root.val:
j = prefix[j]
if pattern[j+1] == root.val:
j += 1
if j+1 == len(pattern):
return True
return dfs(pattern, prefix, root.left, j) or \
dfs(pattern, prefix, root.right, j)
if not head:
return True
pattern, prefix = getPrefix(head)
return dfs(pattern, prefix, root, -1)
# Time: O(n * min(h, l))
# Space: O(h)
# dfs solution
class Solution2(object):
def isSubPath(self, head, root):
"""
:type head: ListNode
:type root: TreeNode
:rtype: bool
"""
def dfs(head, root):
if not head:
return True
if not root:
return False
return root.val == head.val and \
(dfs(head.next, root.left) or
dfs(head.next, root.right))
if not head:
return True
if not root:
return False
return dfs(head, root) or \
self.isSubPath(head, root.left) or \
self.isSubPath(head, root.right)