Skip to content

Commit 331fe6d

Browse files
authored
[mypy] Fix type annotations in data_structures/binary_tree/lowest_common_ancestor.py (TheAlgorithms#5757)
* Fix type annotations in lowest_common_ancestor.py * Refactor line 53 in lowest_common_ancestor.py
1 parent 7954a3a commit 331fe6d

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

data_structures/binary_tree/lowest_common_ancestor.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from __future__ import annotations
55

6-
import queue
6+
from queue import Queue
77

88

99
def swap(a: int, b: int) -> tuple[int, int]:
@@ -37,7 +37,7 @@ def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
3737
# returns lca of node u,v
3838
def lowest_common_ancestor(
3939
u: int, v: int, level: list[int], parent: list[list[int]]
40-
) -> list[list[int]]:
40+
) -> int:
4141
# u must be deeper in the tree than v
4242
if level[u] < level[v]:
4343
u, v = swap(u, v)
@@ -50,7 +50,7 @@ def lowest_common_ancestor(
5050
return u
5151
# moving both nodes upwards till lca in found
5252
for i in range(18, -1, -1):
53-
if parent[i][u] != 0 and parent[i][u] != parent[i][v]:
53+
if parent[i][u] not in [0, parent[i][v]]:
5454
u, v = parent[i][u], parent[i][v]
5555
# returning longest common ancestor of u,v
5656
return parent[0][u]
@@ -61,16 +61,16 @@ def breadth_first_search(
6161
level: list[int],
6262
parent: list[list[int]],
6363
max_node: int,
64-
graph: dict[int, int],
65-
root=1,
64+
graph: dict[int, list[int]],
65+
root: int = 1,
6666
) -> tuple[list[int], list[list[int]]]:
6767
"""
6868
sets every nodes direct parent
6969
parent of root node is set to 0
7070
calculates depth of each node from root node
7171
"""
7272
level[root] = 0
73-
q = queue.Queue(maxsize=max_node)
73+
q: Queue[int] = Queue(maxsize=max_node)
7474
q.put(root)
7575
while q.qsize() != 0:
7676
u = q.get()
@@ -88,7 +88,7 @@ def main() -> None:
8888
parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]
8989
# initializing with -1 which means every node is unvisited
9090
level = [-1 for _ in range(max_node + 10)]
91-
graph = {
91+
graph: dict[int, list[int]] = {
9292
1: [2, 3, 4],
9393
2: [5],
9494
3: [6, 7],

0 commit comments

Comments
 (0)