9
9
3 4 5 6
10
10
11
11
"""
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 :
13
28
"""
14
29
2. Inuition:
15
30
- Use a list to store all ancestors for each node: __ancestors
@@ -30,8 +45,6 @@ class TreeAncestorNaive:
30
45
- Worst case (the tree looks like a linked list): O(n^2) = O(1 + 2 + 3 + ... + n) = O((n + 1) * n/2)
31
46
- Best case (the tree is balanced): O(logn^2) = O(1 + 2 + 3 + ... + logn) = O((logn + 1) * logn/2)
32
47
33
-
34
-
35
48
"""
36
49
def __init__ (self , n : int , parent : List [int ]):
37
50
@@ -54,4 +67,46 @@ def __find_all_ancestors(self, node: int):
54
67
55
68
self .__find_all_ancestors (parent )
56
69
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