The UCX DSA package provides a complete binary search tree (BST) implementation through the Tree and TreeNode classes. A binary search tree is a hierarchical data structure where each node has at most two children, and for every node, all values in the left subtree are smaller and all values in the right subtree are larger.
from dsa.tree import TreeNode# Create a node with a valuenode = TreeNode(10)# Create a node with childrenleft_child = TreeNode(5)right_child = TreeNode(15)parent = TreeNode(10, left=left_child, right=right_child)
The Tree class implements a binary search tree with standard BST operations. It can also be used as a plain binary tree if you manually set nodes without using insert/search/delete operations.
from dsa.tree import Tree# Create and populate a BSTtree = Tree()values = [50, 30, 70, 20, 40, 60, 80]for value in values: tree.insert(value)print(f"Tree size: {len(tree)}") # Output: Tree size: 7# Search for a valuetry: node = tree.search(40) print(f"Found: {node.value}") # Output: Found: 40except ValueError as e: print(e)# Delete a valuetree.delete(30)print(f"After deletion: {len(tree)}") # Output: After deletion: 6# Print the tree structuretree.print()
You can visualize trees using the TreeDraw class from the draw module:
from dsa.tree import Treefrom dsa.draw import TreeDraw# Create and populate a treetree = Tree()for value in [50, 30, 70, 20, 40, 60, 80]: tree.insert(value)# Visualize the treetd = TreeDraw(tree)td.draw() # Display the tree# Or save to a filetd.save("my_tree.png")
The visualization uses NetworkX and Matplotlib to create a hierarchical graph representation of the tree structure.
Worst case occurs when the tree becomes unbalanced (e.g., inserting sorted data). Consider using a self-balancing tree for guaranteed O(log n) operations.