Skip to content

[mypy] Fix type annotations in data_structures/binary_tree/lowest_common_ancestor.py #5757

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions data_structures/binary_tree/lowest_common_ancestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from __future__ import annotations

import queue
from queue import Queue


def swap(a: int, b: int) -> tuple[int, int]:
Expand Down Expand Up @@ -37,7 +37,7 @@ def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
# returns lca of node u,v
def lowest_common_ancestor(
u: int, v: int, level: list[int], parent: list[list[int]]
) -> list[list[int]]:
) -> int:
# u must be deeper in the tree than v
if level[u] < level[v]:
u, v = swap(u, v)
Expand All @@ -50,7 +50,7 @@ def lowest_common_ancestor(
return u
# moving both nodes upwards till lca in found
for i in range(18, -1, -1):
if parent[i][u] != 0 and parent[i][u] != parent[i][v]:
if parent[i][u] not in [0, parent[i][v]]:
u, v = parent[i][u], parent[i][v]
# returning longest common ancestor of u,v
return parent[0][u]
Expand All @@ -61,16 +61,16 @@ def breadth_first_search(
level: list[int],
parent: list[list[int]],
max_node: int,
graph: dict[int, int],
root=1,
graph: dict[int, list[int]],
root: int = 1,
) -> tuple[list[int], list[list[int]]]:
"""
sets every nodes direct parent
parent of root node is set to 0
calculates depth of each node from root node
"""
level[root] = 0
q = queue.Queue(maxsize=max_node)
q: Queue[int] = Queue(maxsize=max_node)
q.put(root)
while q.qsize() != 0:
u = q.get()
Expand All @@ -88,7 +88,7 @@ def main() -> None:
parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]
# initializing with -1 which means every node is unvisited
level = [-1 for _ in range(max_node + 10)]
graph = {
graph: dict[int, list[int]] = {
1: [2, 3, 4],
2: [5],
3: [6, 7],
Expand Down