1
1
# https://en.wikipedia.org/wiki/Lowest_common_ancestor
2
2
# https://en.wikipedia.org/wiki/Breadth-first_search
3
3
4
+ from __future__ import annotations
5
+
4
6
import queue
5
- from typing import Dict , List , Tuple
6
7
7
8
8
- def swap (a : int , b : int ) -> Tuple [int , int ]:
9
+ def swap (a : int , b : int ) -> tuple [int , int ]:
9
10
"""
10
11
Return a tuple (b, a) when given two integers a and b
11
12
>>> swap(2,3)
@@ -21,7 +22,7 @@ def swap(a: int, b: int) -> Tuple[int, int]:
21
22
return a , b
22
23
23
24
24
- def create_sparse (max_node : int , parent : List [ List [int ]]) -> List [ List [int ]]:
25
+ def create_sparse (max_node : int , parent : list [ list [int ]]) -> list [ list [int ]]:
25
26
"""
26
27
creating sparse table which saves each nodes 2^i-th parent
27
28
"""
@@ -35,8 +36,8 @@ def create_sparse(max_node: int, parent: List[List[int]]) -> List[List[int]]:
35
36
36
37
# returns lca of node u,v
37
38
def lowest_common_ancestor (
38
- u : int , v : int , level : List [int ], parent : List [ List [int ]]
39
- ) -> List [ List [int ]]:
39
+ u : int , v : int , level : list [int ], parent : list [ list [int ]]
40
+ ) -> list [ list [int ]]:
40
41
# u must be deeper in the tree than v
41
42
if level [u ] < level [v ]:
42
43
u , v = swap (u , v )
@@ -57,12 +58,12 @@ def lowest_common_ancestor(
57
58
58
59
# runs a breadth first search from root node of the tree
59
60
def breadth_first_search (
60
- level : List [int ],
61
- parent : List [ List [int ]],
61
+ level : list [int ],
62
+ parent : list [ list [int ]],
62
63
max_node : int ,
63
- graph : Dict [int , int ],
64
+ graph : dict [int , int ],
64
65
root = 1 ,
65
- ) -> Tuple [ List [int ], List [ List [int ]]]:
66
+ ) -> tuple [ list [int ], list [ list [int ]]]:
66
67
"""
67
68
sets every nodes direct parent
68
69
parent of root node is set to 0
0 commit comments