Builds the tree for arr and returns the root of the constructed tree >>> build_tree(test_array) Node(min_value=0 max_value=9)
(arr: list[int])
| 33 | |
| 34 | |
| 35 | def build_tree(arr: list[int]) -> Node | None: |
| 36 | """ |
| 37 | Builds the tree for arr and returns the root |
| 38 | of the constructed tree |
| 39 | |
| 40 | >>> build_tree(test_array) |
| 41 | Node(min_value=0 max_value=9) |
| 42 | """ |
| 43 | root = Node(len(arr)) |
| 44 | root.minn, root.maxx = min(arr), max(arr) |
| 45 | # Leaf node case where the node contains only one unique value |
| 46 | if root.minn == root.maxx: |
| 47 | return root |
| 48 | """ |
| 49 | Take the mean of min and max element of arr as the pivot and |
| 50 | partition arr into left_arr and right_arr with all elements <= pivot in the |
| 51 | left_arr and the rest in right_arr, maintaining the order of the elements, |
| 52 | then recursively build trees for left_arr and right_arr |
| 53 | """ |
| 54 | pivot = (root.minn + root.maxx) // 2 |
| 55 | |
| 56 | left_arr: list[int] = [] |
| 57 | right_arr: list[int] = [] |
| 58 | |
| 59 | for index, num in enumerate(arr): |
| 60 | if num <= pivot: |
| 61 | left_arr.append(num) |
| 62 | else: |
| 63 | right_arr.append(num) |
| 64 | root.map_left[index] = len(left_arr) |
| 65 | root.left = build_tree(left_arr) |
| 66 | root.right = build_tree(right_arr) |
| 67 | return root |
| 68 | |
| 69 | |
| 70 | def rank_till_index(node: Node | None, num: int, index: int) -> int: |