Skip to content

Commit

Permalink
#295 another naive solution is added
Browse files Browse the repository at this point in the history
  • Loading branch information
Hamid Gasmi committed Oct 30, 2020
1 parent 3e289fe commit 98ad954
Showing 1 changed file with 59 additions and 4 deletions.
63 changes: 59 additions & 4 deletions 09-problems/lc_1483_kth_ancestor_of_tree_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,22 @@
3 4 5 6
"""
class TreeAncestorNaive:
class TreeAncestorNaive1:
def __init__(self, n: int, parent: List[int]):

self.parent = parent

def getKthAncestor(self, node: int, k: int) -> int:
if not k:
return node

elif not node:
return -1

else:
return self.getKthAncestor(self.parent[node], k - 1)

class TreeAncestorNaive2:
"""
2. Inuition:
- Use a list to store all ancestors for each node: __ancestors
Expand All @@ -30,8 +45,6 @@ class TreeAncestorNaive:
- Worst case (the tree looks like a linked list): O(n^2) = O(1 + 2 + 3 + ... + n) = O((n + 1) * n/2)
- Best case (the tree is balanced): O(logn^2) = O(1 + 2 + 3 + ... + logn) = O((logn + 1) * logn/2)
"""
def __init__(self, n: int, parent: List[int]):

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

self.__find_all_ancestors(parent)
self.__ancestors[node].extend(self.__ancestors[parent])



"""
1. Problem Summary / Clarifications / TDD:
0 1 2 3 4 5 6
parents
0 0 1 1 2 2
0 0 0 0
"""
class TreeAncestorNaiveOptimized:

def __init__(self, n: int, parent: List[int]):

self.parent = parent

self.ancestors = {0:[]}

def getKthAncestor(self, node: int, k: int) -> int:
if node in self.ancestors:
ancestors_len = len(self.ancestors[node])
if k <= ancestors_len:
return self.ancestors[node][k - 1]

elif not node or not self.ancestors[node][-1]:
return -1

else:
ancestor = self.ancestors[node][-1]

else:
ancestor = self.parent[node]
self.ancestors[node] = [ancestor]
ancestors_len = 1

if k - ancestors_len:
self.getKthAncestor(ancestor, k - ancestors_len)
for p in range(ancestors_len - 1):
parent = self.ancestors[node][p]
self.ancestors[parent].extend(self.ancestors[ancestor])
self.ancestors[node].extend(self.ancestors[ancestor])

return self.ancestors[node][k - 1] if k <= len(self.ancestors[node]) else -1

0 comments on commit 98ad954

Please sign in to comment.