Skip to content

Commit 98ad954

Browse files
author
Hamid Gasmi
committed
#295 another naive solution is added
1 parent 3e289fe commit 98ad954

File tree

1 file changed

+59
-4
lines changed

1 file changed

+59
-4
lines changed

09-problems/lc_1483_kth_ancestor_of_tree_node.py

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,22 @@
99
3 4 5 6
1010
1111
"""
12-
class TreeAncestorNaive:
12+
class TreeAncestorNaive1:
13+
def __init__(self, n: int, parent: List[int]):
14+
15+
self.parent = parent
16+
17+
def getKthAncestor(self, node: int, k: int) -> int:
18+
if not k:
19+
return node
20+
21+
elif not node:
22+
return -1
23+
24+
else:
25+
return self.getKthAncestor(self.parent[node], k - 1)
26+
27+
class TreeAncestorNaive2:
1328
"""
1429
2. Inuition:
1530
- Use a list to store all ancestors for each node: __ancestors
@@ -30,8 +45,6 @@ class TreeAncestorNaive:
3045
- Worst case (the tree looks like a linked list): O(n^2) = O(1 + 2 + 3 + ... + n) = O((n + 1) * n/2)
3146
- Best case (the tree is balanced): O(logn^2) = O(1 + 2 + 3 + ... + logn) = O((logn + 1) * logn/2)
3247
33-
34-
3548
"""
3649
def __init__(self, n: int, parent: List[int]):
3750

@@ -54,4 +67,46 @@ def __find_all_ancestors(self, node: int):
5467

5568
self.__find_all_ancestors(parent)
5669
self.__ancestors[node].extend(self.__ancestors[parent])
57-
70+
71+
72+
"""
73+
1. Problem Summary / Clarifications / TDD:
74+
0 1 2 3 4 5 6
75+
parents
76+
0 0 1 1 2 2
77+
0 0 0 0
78+
79+
"""
80+
class TreeAncestorNaiveOptimized:
81+
82+
def __init__(self, n: int, parent: List[int]):
83+
84+
self.parent = parent
85+
86+
self.ancestors = {0:[]}
87+
88+
def getKthAncestor(self, node: int, k: int) -> int:
89+
if node in self.ancestors:
90+
ancestors_len = len(self.ancestors[node])
91+
if k <= ancestors_len:
92+
return self.ancestors[node][k - 1]
93+
94+
elif not node or not self.ancestors[node][-1]:
95+
return -1
96+
97+
else:
98+
ancestor = self.ancestors[node][-1]
99+
100+
else:
101+
ancestor = self.parent[node]
102+
self.ancestors[node] = [ancestor]
103+
ancestors_len = 1
104+
105+
if k - ancestors_len:
106+
self.getKthAncestor(ancestor, k - ancestors_len)
107+
for p in range(ancestors_len - 1):
108+
parent = self.ancestors[node][p]
109+
self.ancestors[parent].extend(self.ancestors[ancestor])
110+
self.ancestors[node].extend(self.ancestors[ancestor])
111+
112+
return self.ancestors[node][k - 1] if k <= len(self.ancestors[node]) else -1

0 commit comments

Comments
 (0)