2025-11-03
Trees Structure
Heaps: Specialized binary trees used to implement priority queues.
Binary Search Trees (BST): Efficiently support dynamic set operations such as search, insert, and delete.
Expression Trees: Used to represent arithmetic expressions, where leaves are operands and internal nodes are operators.
Huffman Coding Trees: Used in data compression algorithms to generate prefix codes.
Syntax Trees: Used in compilers to represent the structure of program code.
File System Indexing: Some file systems use binary trees for efficient file lookup.
Routing Tables: Used in networking for efficient IP routing and searching.
We will discuss the first three
Key in this case is the value used for ordering
interface for a BST should include a constructor and the basic operations common to all collections
isEmpty , len , str , +, == , in , add , and countadd and remove methods__contains__
find and replace are also included.
find expects an item as an argument and returns the item matching it in the tree, or None otherwisereplace expects two items as arguments__iter__ method supports a preorder traversalstr operation returns a string that shows the shape of the tree when printed.| Method | What It Does |
|---|---|
tree.isEmpty() |
Returns True if tree is empty, False otherwise. |
tree.__len__() |
Same as len(tree). Returns the number of items in the tree. |
tree.__str__() |
Same as str(tree). Returns a string showing the shape of the tree when printed. |
tree.__iter__() |
Same as iter(tree) or for item in tree:. Performs a preorder traversal on the tree. |
tree.__contains__(item) |
Same as item in tree. Returns True if item is in the tree, False otherwise. |
tree.__add__(otherTree) |
Same as tree + otherTree. Returns a new tree containing items from both trees. |
tree.__eq__(anyObject) |
Same as tree == anyObject. Returns True if trees are equal (same items in corresponding positions). |
| Method | What It Does |
|---|---|
tree.clear() |
Makes the tree become empty. |
tree.add(item) |
Adds item to its proper place in the tree. |
tree.remove(item) |
Removes item from the tree. Precondition: item is in the tree. |
tree.find(item) |
Returns the matched item if found, otherwise returns None. |
tree.replace(item, newItem) |
Replaces matched item with newItem and returns the matched item, else returns None. |
tree.preorder() |
Returns an iterator for preorder traversal. |
tree.inorder() |
Returns an iterator for inorder traversal. |
tree.postorder() |
Returns an iterator for postorder traversal. |
tree.levelorder() |
Returns an iterator for level order traversal. |
add, remove, find, traversal methods)."""
File: BSTinterface.py
Author: Ken Lambert
"""
class BSTInterface(object):
"""Interface for all binary search trees."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
pass
# Accessor methods
def isEmpty(self):
"""Returns True if len(self) == 0, or False otherwise."""
return True
def __len__(self):
"""-Returns the number of items in self."""
return 0
def __str__(self):
"""Returns the string representation of self."""
return ""
def __iter__(self):
"""Supports a preorder traversal on a view of self."""
return None
def inorder(self):
"""Supports an inorder traversal on a view of self."""
return None
def postorder(self):
"""Supports a postorder traversal on a view of self."""
return None
def levelorder(self):
"""Supports a levelorder traversal on a view of self."""
return None
def __add__(self, other):
"""Returns a new bag containing the contents
of self and other."""
return None
def __eq__(self, other):
"""Returns True if self equals other,
or False otherwise."""
return False
def __contains__(self, item):
"""Returns Ture if item is in self, or
False otherwise."""
return True
def find(self, item):
"""If item matches an item in self, returns the
matched item, or None otherwise."""
return None
# Mutator methods
def clear(self):
"""Makes self become empty."""
pass
def add(self, item):
"""Adds item to self."""
pass
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item is not in self.
postcondition: item is removed from self."""
pass
def replace(self, item, newItem):
"""Precondition: item == newItem.
Raises: KeyError if item != newItem.
If item is in self, replaces it with newItem and
returns the old item, or returns None otherwise."""
return NoneisEmpty, __len__, clear)."""
File: abstractcollection.py
Author: Ken Lambert
"""
class AbstractCollection(object):
"""An abstract collection implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
self.size = 0
if sourceCollection:
for item in sourceCollection:
self.add(item)
# Accessor methods
def isEmpty(self):
"""Returns True if len(self) == 0, or False otherwise."""
return len(self) == 0
def __len__(self):
"""Returns the number of items in self."""
return self.size
def __str__(self):
"""Returns the string representation of self."""
return "[" + ", ".join(map(str, self)) + "]"
def __add__(self, other):
"""Returns a new bag containing the contents
of self and other."""
result = type(self)(self)
for item in other:
result.add(item)
return result
def __eq__(self, other):
"""Returns True if self equals other,
or False otherwise."""
if self is other: return True
if type(self) != type(other) or \
len(self) != len(other):
return False
otherIter = iter(other)
for item in self:
if item != next(otherIter):
return False
return True
def count(self, item):
"""Returns the number of instances of item in self."""
total = 0
for nextItem in self:
if nextItem == item:
total += 1
return total"""
File: linkedbst.py
Author: Ken Lambert
"""
from abstractcollection import AbstractCollection
from bstnode import BSTNode
class LinkedBST (AbstractCollection):
"""An link-based binary search tree implementation."""
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
self.root = None
AbstractCollection.__init__(self, sourceCollection)
# Implement add, remove, find, __contains__, __iter__, etc.Preorder, inorder, postorder, and level order traversals as generator methods.find method returns the first matching item if the target item is in the treedef __str__(self):
"""Returns a string representation with the tree rotated
90 degrees counterclockwise."""
def recurse(node, level):
s = ""
if node != None:
s += recurse(node.right, level + 1)
s += "| " * level
s += str(node.data) + "\n"
s += recurse(node.left, level + 1)
return s
return recurse(self.root, 0)add method inserts an item into its proper place in the binary search treeadd method uses a recursive helper function named recursedef add(self, item):
"""Adds item to the tree."""
# Helper function to search for item’s position
def recurse(node):
# New item is less; go left until spot is found
if item < node.data:
if node.left == None:
node.left = BSTNode(item)
else:
recurse(node.left)
# New item is greater or equal;
# go right until spot is found
elif node.right == None:
node.right = BSTNode(item)
else:
recurse(node.right)
# End of recurse
# Tree is empty, so new item goes at the root
if self.isEmpty():
self.root = BSTNode(item)
# Otherwise, search for the item’s spot
else:
recurse(self.root)
self.size += 1