forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKth Ancestor of a Tree Node.py
40 lines (28 loc) · 999 Bytes
/
Kth Ancestor of a Tree Node.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
from math import ceil, log2
from typing import List
NO_PARENT = -1
class TreeAncestor:
def __init__(self, n: int, parent: List[int]):
self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))]
self.__initialize(parent)
def __initialize(self, parent: List[int]):
self.parent[0], prev = parent, parent
for jump_pow in range(1, len(self.parent)):
cur = self.parent[jump_pow]
for i, p in enumerate(prev):
if p != NO_PARENT:
cur[i] = prev[p]
prev = cur
def getKthAncestor(self, node: int, k: int) -> int:
jump_pow = self.jump_pow
while k > 0 and node != NO_PARENT:
jumps = 1 << jump_pow
if k >= jumps:
node = self.parent[jump_pow][node]
k -= jumps
else:
jump_pow -= 1
return node
@property
def jump_pow(self) -> int:
return len(self.parent) - 1