Skip to content

Commit cbf8f62

Browse files
committed
feat(datastructures, bst): construct min height bst
1 parent b78b639 commit cbf8f62

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

datastructures/trees/binary/search_tree/__init__.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,36 @@ def __init__(self, root: Optional[BinaryTreeNode] = None):
1212
super().__init__(root)
1313
self.stack = DynamicSizeStack()
1414

15+
@staticmethod
16+
def construct_bst(items: List[T]) -> Optional['BinarySearchTree']:
17+
"""
18+
Constructs a binary search tree from a sorted list of items.
19+
20+
This method works by recursively finding the middle element of the list and assigning it to the root of the tree.
21+
The left and right subtrees are then constructed by recursively calling the method on the left and right halves
22+
of the list.
23+
24+
@param items: A sorted list of items to construct the tree from.
25+
@return: A binary search tree constructed from the items.
26+
"""
27+
if not items:
28+
return None
29+
30+
def construct_bst_helper(left: int, right: int) -> Optional[BinaryTreeNode]:
31+
# base case for the method if the left is greater than the right
32+
if left > right:
33+
return None
34+
35+
# Find the middle index - this element becomes the root
36+
# Using (left + right) // 2 ensures we get the left-middle for even-length arrays
37+
mid = (left + right) // 2
38+
root = BinaryTreeNode(items[mid])
39+
root.left = construct_bst_helper(left, mid - 1)
40+
root.right = construct_bst_helper(mid + 1, right)
41+
return root
42+
43+
return BinarySearchTree(root=construct_bst_helper(0, len(items) - 1))
44+
1545
def insert_node(self, data: T):
1646
"""
1747
Inserts a node in a BST given an element

0 commit comments

Comments
 (0)