1
+ """
2
+ 1. Problem Summary / Clarifications / TDD:
3
+ Parent : -1 0 0 1 1 2 2
4
+ Node no: 0 1 2 3 4 5 6
5
+ 0
6
+ / \
7
+ 1 2
8
+ / \ / \
9
+ 3 4 5 6
10
+
11
+ """
12
+ class TreeAncestorNaive :
13
+ """
14
+ 2. Inuition:
15
+ - Use a list to store all ancestors for each node: __ancestors
16
+ - The kth ancestor of node k will be stored in: __ancestors[node][k - 1]
17
+
18
+ 3. Implementation:
19
+ 4. Tests:
20
+
21
+ 5. Complexity Analysis:
22
+ Time Complexity:
23
+ - Constructor: O(1)
24
+ - Get kth ancestor: O(n^2)
25
+ - Worst case (the tree looks like a linked list): O(n^2) = O(1 + 2 + 3 + ... + n) = O((n + 1) * n/2)
26
+ - Best case (the tree is balanced): O(logn^2) = O(1 + 2 + 3 + ... + logn) = O((logn + 1) * logn/2)
27
+ Space Complexity:
28
+ - Constructor: O(1)
29
+ - Get kth ancestor: O(n^2)
30
+ - Worst case (the tree looks like a linked list): O(n^2) = O(1 + 2 + 3 + ... + n) = O((n + 1) * n/2)
31
+ - Best case (the tree is balanced): O(logn^2) = O(1 + 2 + 3 + ... + logn) = O((logn + 1) * logn/2)
32
+
33
+
34
+
35
+ """
36
+ def __init__ (self , n : int , parent : List [int ]):
37
+
38
+ self .parent = parent
39
+
40
+ self .__ancestors = {0 :[]}
41
+
42
+ def getKthAncestor (self , node : int , k : int ) -> int :
43
+ if node not in self .__ancestors :
44
+ self .__find_all_ancestors (node )
45
+
46
+ return self .__ancestors [node ][k - 1 ] if k <= len (self .__ancestors [node ]) else - 1
47
+
48
+ def __find_all_ancestors (self , node : int ):
49
+ if node in self .__ancestors :
50
+ return
51
+
52
+ parent = self .parent [node ]
53
+ self .__ancestors [node ] = [parent ]
54
+
55
+ self .__find_all_ancestors (parent )
56
+ self .__ancestors [node ].extend (self .__ancestors [parent ])
57
+
0 commit comments