btree_9
index
/home/tom/py/btree_9.py

# ===================================================================
# The balance algorithem tries to balance a new node's
# child nodes everytime a new node is inserted into the tree
# ===================================================================
# create a sort of balanced tree
#
# The node class in this code has only one data item. It is the
# node's data and also is the node's unique key. In the
# "real world" a node would contain much more data and perhaps
# have a unique key that is seperate from the node's data.
#
# Note: A node's unique key is used to position a node's place
#       in the tree.
# ===================================================================
# Tree Functions...
# tree.debug                  set debug flag
# tree.balance                set balance processing flag
# tree.count_nodes            return the number of nodes in the tree
# tree.max_height             return the max depth (levels) in the tree
# tree.avg_height             return average search depth in the tree
# tree.insert                 insert node into tree
# tree.search                 search for a value (node) in the tree
# tree.remove_leaf_node       remove a leaf node from the tree
# tree.print_tree_nodes       print the tree node information
# tree.print_tree_values      print the tree node values 
# tree.Print_tree_structure   print the tree structure
# ===================================================================
# Note about the code:
# a. curnode is the current working node
# b. newnode is the node being added to the tree
# c. parnode is the parent node of current working node
# d. the tree root node is modified but not replaced
# e. the BinaryTree class has two special methods. They control
#    BinaryTree operations. they are:
#      tree.set_debug()    print messages used for debugging
#      tree.set_balance()  use my balance "stuff" when creating the tree
# ===================================================================
#
# Testing:
#
# from random import randint
# from random import sample
# import btree_9 as bt9
#
# # ---- function - create random node values -----------------------
# # ----            with potential duplicates -----------------------
#
# def create_random_node_values_dups(elms=20,maxint=100):
#     values  = []
#     for _ in range(elms):
#         values.append(randint(1,maxint))
#     return values
#
# # ---- function - create random node values -----------------------
# # ----            with no duplicates ------------------------------
#
# def create_random_node_values(elms=20,maxint=100):
#     values = sample(range(1,maxint),elms)
#     return values
#
# #---- function - fill a tree with nodes (values) ------------------
#
# def fill_tree(tree,values):
#     for i in values:
#         tree.insert(bt9.Node(i))
#
# # ---- test values ------------------------------------------------
#
# ##values = [30,20,10,5,1,40,50,60,70]
# ##values = [30,40,50,60,70]
# ##values = [30,20,10,5,1]
# ##values = [10,9,8,7,6,5,4,3,2,1,11,12,13,14,15,16,17,18,19]
#
# values = create_random_node_values(100,10000)
#
# print('\n---- create un-balanced tree --------------------------')
#
# tree = bt9.BinaryTree()
# tree.set_balance(False)
# tree.set_debug(False)
# fill_tree(tree,values)
# ##tree.print_tree_values()
# ##tree.print_tree_nodes()
# tree.print_tree_structure()
# print("Maximum height of tree is {}".format(tree.max_height()))
# print("Average height of tree is {}".format(tree.avg_height()))
#
# print('\n---- create a sort of balanced tree -------------------')
#
# tree = bt9.BinaryTree()
# tree.set_balance(True)
# tree.set_debug(False)
# fill_tree(tree,values)
# ##tree.print_tree_values()
# ##tree.print_tree_nodes()
# tree.print_tree_structure()
# print("Maximum height of tree is {}".format(tree.max_height()))
# print("Average height of tree is {}".format(tree.avg_height()))
#
# ===================================================================

 
Modules
       
numpy

 
Classes
       
BinaryTree
Node

 
class BinaryTree
     Methods defined here:
__init__(self)
Constructor for the BinaryTree class.
 
Attributes:
  root      The root node of the btree.
            Initially it is set to None. The first node
            inserted into the btree becomes the root node.
  balance   If True, try to ballance the current node.
  debug     If True, print debug messages.
avg_height(self)
Return the average number of levels in a tree.
 
Note: only paths to leaf nodes are used in this
      calculation. That is because we are looking
      at worst case (not found) searches.
 
Note: Because the Python scoping rules suck,
      I am using the list x where:
      x[0] = total leaf node path lengths
      x[1] = number of leaf node paths
count_nodes(self)
return the number of nodes in a tree.
insert(self, newnode)
Insert a new node into the tree.
max_height(self)
Return the maximum number of levels in a tree.
print_tree_nodes(self, sep1='', sep2='')
print a tree nodes - one per line
print_tree_structure(self)
print a tree's structure
print_tree_values(self)
print a tree's values - one per line
remove_leaf_node(self, value)
Remove a node from the tree.
search(self, value)
Search a tree for a node (value) and return the
node value. Return None if not found.
set_balance(self, flag=False)
Set "create balanced tree" flag. The default is False.
set_debug(self, flag=False)
Set debug flag. The default is False.

 
class Node
    This class defines nodes to be inserted into a btree.
 
This class is a container for user define data. The
only required field is 'data' which is a unique key
used to position a node in the btree and contain
user data.
 
  Methods defined here:
__init__(self, data, print_flag=False)
Constructor for btree Node class.
 
Attributes:
  data (int):    node data and node unique key used to
                 position the node in the btree.
  left (node):   link to the root node of a subtree
                 containing nodes with with data (keys)
                 less than this node.
  right (node):  link to the root node of a subtree
                 containing nodes with with data (keys)
                 greater than this node.
  parent (node): link to this node's parent node in the
                 tree. If there is no parent (tree's
                 root node) the link is set to None.
 
Parameters:
  data:  A node's data (key) value.
  flag:  A Flag to print debug information. True will
         print information. False will not. If this
         parameter is not provided the default is False.
print_node(self, title='', single_line=True)
Print node information in one of two ways.
single line or multiline.
 
Parameters:
   title (str):        A string to print before printing the
                       node information.
   single_line (bool): If True a single line is print if
                       not True multiple lines are printed.
                       If title is None, an empty string, or
                       not provided no title is printed.