A complete binary search tree is a complete binary tree that satisfies the left-right ordering property of binary search tree as well as the structure of a complete binary tree. Since a complete binary tree can be perfectly stored in an array, we can also store the complete BST in an array. In this lab, you will be given an array of integers as input. The objective is to write a function to_bst(lst) to convert the array to a complete binary tree that stores in an array with the same length. For example, given an array [29, 72, 1, 34, 22], the corresponding complete BST is [34, 22, 72, 1, 29]. Hint: Consider the inorder traversal of the BST. For example: Test Result keys = [29, 72, 1, 34, 22] to_bst(keys) print(keys)
时间: 2023-12-14 12:40:20 浏览: 45
To convert the given array to a complete BST, we need to perform the following steps:
1. Sort the array in ascending order
2. Construct a complete binary tree using the sorted array
3. Perform inorder traversal of the binary tree and store the elements in the original array in the same order as the traversal
Here's the implementation of the to_bst(lst) function in Python:
```python
def to_bst(lst):
# Sort the input list
lst.sort()
# Construct a complete binary tree using the sorted list
n = len(lst)
if n == 0:
return lst
root = lst[n // 2]
left_subtree = to_bst(lst[:n // 2])
right_subtree = to_bst(lst[n // 2 + 1:])
binary_tree = [root] + left_subtree + right_subtree
# Perform inorder traversal of the binary tree and store the elements in the original array
inorder_traversal(binary_tree, lst, 0)
return lst
def inorder_traversal(binary_tree, lst, i):
# Perform inorder traversal of the binary tree and store the elements in the original array
n = len(binary_tree)
if i >= n:
return
inorder_traversal(binary_tree, lst, 2 * i + 1)
lst[i] = binary_tree[i]
inorder_traversal(binary_tree, lst, 2 * i + 2)
```
The to_bst(lst) function takes in the input list and returns the same list after converting it to a complete BST. The function first sorts the input list in ascending order. It then constructs a complete binary tree using the sorted list by recursively dividing the list into two halves and setting the middle element as the root of the binary tree. Finally, the function performs an inorder traversal of the binary tree and stores the elements in the original list in the same order as the traversal.