Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perf
(
height: int = 3,
is_perfect: bool = False,
letters: bool = False,
)
| 2305 | |
| 2306 | |
| 2307 | def tree( |
| 2308 | height: int = 3, |
| 2309 | is_perfect: bool = False, |
| 2310 | letters: bool = False, |
| 2311 | ) -> Optional[Node]: |
| 2312 | """Generate a random binary tree and return its root node. |
| 2313 | |
| 2314 | :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). |
| 2315 | :type height: int |
| 2316 | :param is_perfect: If set to True (default: False), a perfect binary tree |
| 2317 | with all levels filled is returned. If set to False, a perfect binary |
| 2318 | tree may still be generated by chance. |
| 2319 | :type is_perfect: bool |
| 2320 | :param letters: If set to True (default: False), uppercase alphabet letters are |
| 2321 | used for node values instead of numbers. |
| 2322 | :type letters: bool |
| 2323 | :return: Root node of the binary tree. |
| 2324 | :rtype: binarytree.Node |
| 2325 | :raise binarytree.exceptions.TreeHeightError: If height is invalid. |
| 2326 | |
| 2327 | **Example**: |
| 2328 | |
| 2329 | .. doctest:: |
| 2330 | |
| 2331 | >>> from binarytree import tree |
| 2332 | >>> |
| 2333 | >>> root = tree() |
| 2334 | >>> |
| 2335 | >>> root.height |
| 2336 | 3 |
| 2337 | |
| 2338 | .. doctest:: |
| 2339 | |
| 2340 | >>> from binarytree import tree |
| 2341 | >>> |
| 2342 | >>> root = tree(height=5, is_perfect=True) |
| 2343 | >>> |
| 2344 | >>> root.height |
| 2345 | 5 |
| 2346 | >>> root.is_perfect |
| 2347 | True |
| 2348 | |
| 2349 | .. doctest:: |
| 2350 | |
| 2351 | >>> from binarytree import tree |
| 2352 | >>> |
| 2353 | >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL |
| 2354 | Traceback (most recent call last): |
| 2355 | ... |
| 2356 | binarytree.exceptions.TreeHeightError: height must be an int between 0 - 9 |
| 2357 | """ |
| 2358 | _validate_tree_height(height) |
| 2359 | numbers = _generate_random_numbers(height) |
| 2360 | values: NodeValueList = ( |
| 2361 | list(map(number_to_letters, numbers)) if letters else numbers |
| 2362 | ) |
| 2363 | |
| 2364 | if is_perfect: |