-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathclosest-nodes-queries-in-a-binary-search-tree.py
83 lines (72 loc) · 2.18 KB
/
closest-nodes-queries-in-a-binary-search-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
# Time: O(n + qlogn)
# Space: O(n)
import bisect
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
pass
# iterative dfs, binary search
class Solution(object):
def closestNodes(self, root, queries):
"""
:type root: Optional[TreeNode]
:type queries: List[int]
:rtype: List[List[int]]
"""
def iter_dfs():
inorder = []
stk = [(1, root)]
while stk:
step, node = stk.pop()
if step == 1:
if not node:
continue
stk.append((1, node.right))
stk.append((2, node))
stk.append((1, node.left))
elif step == 2:
inorder.append(node.val)
return inorder
inorder = iter_dfs()
result = []
for q in queries:
i = bisect.bisect_left(inorder, q)
if i == len(inorder):
result.append([inorder[i-1], -1])
elif inorder[i] == q:
result.append([inorder[i], inorder[i]])
elif i-1 >= 0:
result.append([inorder[i-1], inorder[i]])
else:
result.append([-1, inorder[i]])
return result
# Time: O(n + qlogn)
# Space: O(n)
import bisect
# dfs, binary search
class Solution2(object):
def closestNodes(self, root, queries):
"""
:type root: Optional[TreeNode]
:type queries: List[int]
:rtype: List[List[int]]
"""
def dfs(node):
if not node:
return
dfs(node.left)
inorder.append(node.val)
dfs(node.right)
inorder = []
dfs(root)
result = []
for q in queries:
i = bisect.bisect_left(inorder, q)
if i == len(inorder):
result.append([inorder[i-1], -1])
elif inorder[i] == q:
result.append([inorder[i], inorder[i]])
elif i-1 >= 0:
result.append([inorder[i-1], inorder[i]])
else:
result.append([-1, inorder[i]])
return result