MCPcopy
hub / github.com/joowani/binarytree / bst

Function bst

binarytree/__init__.py:2392–2465  ·  view source on GitHub ↗

Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a

(
    height: int = 3,
    is_perfect: bool = False,
    letters: bool = False,
)

Source from the content-addressed store, hash-verified

2390
2391
2392def bst(
2393 height: int = 3,
2394 is_perfect: bool = False,
2395 letters: bool = False,
2396) -> Optional[Node]:
2397 """Generate a random BST (binary search tree) and return its root node.
2398
2399 :param height: Height of the BST (default: 3, range: 0 - 9 inclusive).
2400 :type height: int
2401 :param is_perfect: If set to True (default: False), a perfect BST with all
2402 levels filled is returned. If set to False, a perfect BST may still be
2403 generated by chance.
2404 :type is_perfect: bool
2405 :param letters: If set to True (default: False), uppercase alphabet letters are
2406 used for node values instead of numbers.
2407 :type letters: bool
2408 :return: Root node of the BST.
2409 :rtype: binarytree.Node
2410 :raise binarytree.exceptions.TreeHeightError: If height is invalid.
2411
2412 **Example**:
2413
2414 .. doctest::
2415
2416 >>> from binarytree import bst
2417 >>>
2418 >>> root = bst()
2419 >>>
2420 >>> root.height
2421 3
2422 >>> root.is_bst
2423 True
2424
2425 .. doctest::
2426
2427 >>> from binarytree import bst
2428 >>>
2429 >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL
2430 Traceback (most recent call last):
2431 ...
2432 binarytree.exceptions.TreeHeightError: height must be an int between 0 - 9
2433 """
2434 _validate_tree_height(height)
2435 if is_perfect:
2436 return _generate_perfect_bst(height)
2437
2438 numbers = _generate_random_numbers(height)
2439 values: NodeValueList = (
2440 list(map(number_to_letters, numbers)) if letters else numbers
2441 )
2442 leaf_count = _generate_random_leaf_count(height)
2443
2444 root_node = Node(values.pop(0))
2445 leaves = set()
2446
2447 for value in values:
2448 node = root_node
2449 depth = 0

Callers 1

test_bst_generationFunction · 0.90

Calls 5

_validate_tree_heightFunction · 0.85
_generate_perfect_bstFunction · 0.85
_generate_random_numbersFunction · 0.85
NodeClass · 0.85

Tested by 1

test_bst_generationFunction · 0.72