Skip to content

Instantly share code, notes, and snippets.

@AmosAidoo
Created October 5, 2020 13:03
Show Gist options
  • Save AmosAidoo/adb3da57f74a2d9923446b87e539b279 to your computer and use it in GitHub Desktop.
Save AmosAidoo/adb3da57f74a2d9923446b87e539b279 to your computer and use it in GitHub Desktop.
Solution
def solution(h, q):
root = (1 << h) - 1
l = h-1
queue = [root-(1<<l), root-1]
parent = [0 for _ in range(root+1)]
parent[root] = -1
parent[queue[0]] = root
parent[queue[1]] = root
pows = 2
while l > 1:
l -= 1
for i in range(pows):
root = queue[0]
leftChild = root-(1<<l)
rightChild = root-1
queue.append(leftChild)
queue.append(rightChild)
parent[leftChild] = root
parent[rightChild] = root
queue.pop(0)
pows <<= 1
ans = []
for element in q:
ans.append(parent[element])
return ans
print(solution(3, [1,4,7]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment