Skip to content

Commit

Permalink
Merge pull request #19 from UBC-MDS/function_list_to_tree
Browse files Browse the repository at this point in the history
Create function and change ReadMe
  • Loading branch information
javiermtzo99 authored Jan 11, 2025
2 parents b417659 + d600e68 commit 40e34c5
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 33 deletions.
77 changes: 44 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
# datastructpy

Data Structures for Python
datastructpy is a Python package designed to provide customizable and practical implementations of essential data structures. It is tailored to help users prepare for technical interviews and coding challenges by offering intuitive, modular, and efficient solutions. The library emphasizes clarity and functionality, making it a valuable resource for learning, practicing, and mastering data structure concepts. Whether you’re solving algorithmic problems or building foundational coding skills, datastructpy is crafted to support your success.

## Functions Included:
## Data Structures Included:

- **`insert(root, key)`**:
- This function inserts a specified key into a Binary Search Tree (BST) by recursively finding the correct position while maintaining BST properties, creating a new root node if the tree is empty, inserting into the left subtree if the key is smaller, or the right subtree if larger.
- **`delete(root, key)`**:
- This function deletes a specified key from a Binary Search Tree (BST). If the key is found, it removes the node while maintaining BST properties. For nodes with two children, it replaces the node with its in-order successor (smallest value in the right subtree) and then deletes the successor node. If the node has one child or no children, it is removed, and its child (if any) takes its place.

- ### `Binary Search Tree`
A Binary Search Tree (BST) is a data structure that organizes data hierarchically, allowing for efficient insertion, deletion, and lookup operations. Each node in the tree contains a key, and the tree is structured such that:
- Keys in the left subtree of a node are smaller than the node’s key.
- Keys in the right subtree of a node are larger than the node’s key.
- Duplicate keys are not allowed.

**Methods**
- **`insert(root, key)`**:
- This method inserts a specified key into a Binary Search Tree (BST) by recursively finding the correct position while maintaining BST properties, creating a new root node if the tree is empty, inserting into the left subtree if the key is smaller, or the right subtree if larger.
- **`delete(root, key)`**:
- This method deletes a specified key from a Binary Search Tree (BST). If the key is found, it removes the node while maintaining BST properties. For nodes with two children, it replaces the node with its in-order successor (smallest value in the right subtree) and then deletes the successor node. If the node has one child or no children, it is removed, and its child (if any) takes its place.
- **`list_to_tree(elements)`**:
- This static method constructs a Binary Search Tree (BST) from a given list of elements. It sequentially inserts each element into the BST, ensuring the tree maintains its BST properties. The method is accessed directly via the BinarySearchTree class and returns a BinarySearchTree object with the provided elements organized in a valid BST structure.

## datastructpy in Python Ecosystem
datastructpy complements Python’s standard library by providing customizable implementations of essential data structures for learning and interview preparation. While modules like collections (e.g., deque) and heapq focus on optimized, ready-to-use structures, datastructpy emphasizes clarity and adaptability, making it ideal for understanding core concepts. Unlike specialized libraries like [pyrsistent](https://pypi.org/project/pyrsistent/) or [sortedcontainers](https://pypi.org/project/sortedcontainers/), datastructpy bridges the gap between practical functionality and educational needs, carving out a unique space in the Python ecosystem.

## Installation

Expand All @@ -18,45 +29,45 @@ $ pip install datastructpy

## Usage

### insert(root, key):

This function inserts a specified key into a Binary Search Tree (BST). It traverses the tree recursively to find the correct position where the key should be placed, ensuring that the BST properties are maintained. If the root is None, a new node is created as the root. If the key is smaller than the current node's key, it is inserted in the left subtree. If the key is larger than the current node's key, it is inserted in the right subtree.

### Example usage:

```python
from datastructpy.binary_search_tree import Node, BinarySearchTree
from datastructpy.binary_search_tree import BinarySearchTree

# Create a Binary Search Tree
bst = BinarySearchTree()
bst.insert(10) # Insert root
bst.insert(5) # Insert left child
bst.insert(15) # Insert right child
bst.insert(8) # Insert into left subtree
# Create a Binary Search Tree from a list of elements
elements = [10, 5, 15, 8]
bst = BinarySearchTree.list_to_tree(elements)

# Check the structure of the tree
print("Tree Structure After Creation:")
print(bst.root.key) # Output: 10
print(bst.root.left.key) # Output: 5
print(bst.root.right.key) # Output: 15
print(bst.root.left.right.key) # Output: 8
```

### delete(root, key):
This function deletes a specified key from a Binary Search Tree (BST). If the key matches a node in the tree, the function removes the node while ensuring that BST properties are maintained. For nodes with two children, it finds the in-order successor, replaces the node's key with the successor's key, and deletes the successor node. If the node has only one child or no children, the node is removed, and its child (if present) takes its place.

### Example usage:

```python
from datastructpy.binary_search_tree import Node, BinarySearchTree

# Using the tree created above
# Insert new nodes into the BST
print("Inserting New Elements:")
bst.insert(12) # Insert into right subtree of 10
bst.insert(2) # Insert into left subtree of 5
print(bst.root.right.left.key) # Output: 12 (right subtree of 10, left child of 15)
print(bst.root.left.left.key) # Output: 2 (left child of 5)

# Delete a node
bst.delete(5) # Delete left child
print(bst.root.left) # Output: None (since 5 is deleted)

bst.delete(10) # Delete root
print(bst.root.key) # Output: 15 (new root after deletion)
print("Deleting Nodes:")
bst.delete(5) # Delete the left child of the root
if bst.root.left:
print(bst.root.left.key) # Output: 8 (5 replaced by its in-order successor)
else:
print(bst.root.left) # Output: None (if successor is not present)

bst.delete(10) # Delete the root
print(bst.root.key) # Output: 15 (new root after deletion)

# Final structure of the tree
print("Final Tree Structure:")
print(bst.root.key) # Output: 15
print(bst.root.left.key) # Output: 8
print(bst.root.right.left.key) # Output: 12
```

## Contributing
Expand Down
33 changes: 33 additions & 0 deletions src/datastructpy/datastructpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,37 @@ def delete(self, key):
bst.delete(5) # Delete a leaf node
print(bst.root.left) # Output: None
"""

@staticmethod
def list_to_tree(elements):
"""
Constructs a Binary Search Tree (BST) from a list of elements.
This function takes a list of numerical values and inserts them into a BST
in the order they appear in the list. Duplicate values are ignored
to maintain the properties of a BST.
Parameters
----------
elements : list of int
A list of integers to be inserted into the BST.
Returns
-------
BinarySearchTree
A BinarySearchTree object containing all the elements from the input list.
Raises
------
ValueError
If the input is not a list or contains non-integer elements.
Examples
--------
# Creating a BST from a list of values
elements = [10, 5, 15, 12, 20]
bst = BinarySearchTree.list_to_tree(elements)
print(bst.root.key) # Output: 10 (root node)
print(bst.root.left.key) # Output: 5 (left child of root)
print(bst.root.right.key) # Output: 15 (right child of root)
"""

0 comments on commit 40e34c5

Please sign in to comment.