Skip to content

Commit a82ab09

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent c8ac042 commit a82ab09

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

data_structures/binary_tree/lowest_common_ancestor.py

+16-16
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,21 @@ def swap(a: int, b: int) -> tuple[int, int]:
2525
def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
2626
"""
2727
Create a sparse table that saves each node's 2^i-th parent.
28-
28+
2929
The given ``parent`` table should have the direct parent of each node in row 0.
3030
This function fills in:
31-
31+
3232
parent[j][i] = parent[j - 1][parent[j - 1][i]]
33-
33+
3434
for each j where 2^j is less than max_node.
35-
35+
3636
For example, consider a small tree where:
3737
- Node 1 is the root (its parent is 0),
3838
- Nodes 2 and 3 have parent 1.
39-
39+
4040
We set up the parent table for only two levels (row 0 and row 1)
4141
for max_node = 3. (Note that in practice the table has many rows.)
42-
42+
4343
>>> parent0 = [0, 0, 1, 1] # 0 is unused; node1's parent=0, nodes 2 and 3's parent=1.
4444
>>> parent1 = [0, 0, 0, 0]
4545
>>> parent = [parent0, parent1]
@@ -61,11 +61,11 @@ def lowest_common_ancestor(
6161
) -> int:
6262
"""
6363
Return the lowest common ancestor (LCA) of nodes u and v in a tree.
64-
64+
6565
The lists ``level`` and ``parent`` must be precomputed. ``level[i]`` is the depth
6666
of node i, and ``parent`` is a sparse table where parent[0][i] is the direct parent
6767
of node i.
68-
68+
6969
>>> # Consider a simple tree:
7070
>>> # 1
7171
>>> # / \\
@@ -106,10 +106,10 @@ def breadth_first_search(
106106
) -> tuple[list[int], list[list[int]]]:
107107
"""
108108
Run a breadth-first search (BFS) from the root node of the tree.
109-
109+
110110
This sets each node's direct parent (stored in parent[0]) and calculates the
111111
depth (level) of each node from the root.
112-
112+
113113
>>> # Consider a simple tree:
114114
>>> # 1
115115
>>> # / \\
@@ -140,27 +140,27 @@ def main() -> None:
140140
"""
141141
Run a BFS to set node depths and parents in a sample tree, then create the
142142
sparse table and compute several lowest common ancestors.
143-
143+
144144
The sample tree used is:
145-
145+
146146
1
147-
/ | \
147+
/ | \
148148
2 3 4
149149
/ / \\ \\
150150
5 6 7 8
151151
/ \\ | / \\
152152
9 10 11 12 13
153-
153+
154154
The expected lowest common ancestors are:
155155
- LCA(1, 3) --> 1
156156
- LCA(5, 6) --> 1
157157
- LCA(7, 11) --> 3
158158
- LCA(6, 7) --> 3
159159
- LCA(4, 12) --> 4
160160
- LCA(8, 8) --> 8
161-
161+
162162
To test main() without it printing to the console, we capture the output.
163-
163+
164164
>>> import sys
165165
>>> from io import StringIO
166166
>>> backup = sys.stdout

0 commit comments

Comments
 (0)