You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12 KiB

a binary tree of leaves of letters

In [ ]:
# http://syllabus.cs.manchester.ac.uk/ugt/2021/COMP26912/lab/ex5.html
# https://web.stanford.edu/class/archive/cs/cs106x/cs106x.1174/assn/twentyOneQuestions.html
# https://www.openbookproject.net/py4fun/animal/animal.html
In [330]:
# each leaf stores a letter to be asked
class letterLeaf:
    def __init__(self,letter):
        self.leftAlphabet = None
        self.rightAlphabet = None
        self.letter = letter
        # try using a list structure to contain the words in this node? 
        self.words = []
In [331]:
# tree traversals, here to print stuff 
def inorder(treeName):
    if treeName:
        inorder(treeName.leftAlphabet)
        print(treeName.letter)
        inorder(treeName.rightAlphabet)
In [332]:
# printing tree utility 
# this segment is modified from Shubham Singh(SHUBHAMSINGH10)'s contribution 

# spacer
COUNT = [10]

# print a flat lying tree
# speculation this is a recursion that prints the right leaf until there is nothing left
def print2DUtil_flat(root, space) :
    # Base case
    if (root == None) :
        return
    # Increase distance between levels
    space += COUNT[0]
    # Process right leaf/branch/child first
    print2DUtil_flat(root.rightAlphabet, space)
    print()
    for i in range(COUNT[0], space):
        print(end = " ")
    print(root.letter)
    # Process left child
    print2DUtil_flat(root.leftAlphabet, space)

    # Wrapper over print2DUtil()
def print2D(root) :
    #Pass initial space count as 0
    print("here is a tree that's laying on the ground: ")
    print2DUtil_flat(root, 0)
In [333]:
# utility to read the first letter of the input word 
# press enter key, otherwise notebook will be pending
def grepFirstLetter():
    word = input()
    firstLetter = word[0]
    return firstLetter
    #print("the letter starts with : {}, and will be inserted under the {} leaf".format(firstLetter, firstLetter))
In [334]:
def insertLeaf(root,firstLetter):
    #create new leaf 
    letterLeaf(firstLetter)
    # python pointer implementation
    # a root pointer 
    x = root
    # pointer y maintains the trailing
    # pointer of x
    y = None
    # traversal 
    # while x != none means the pointer can keep traversing
    while(x != None):
        y = x #trailing pointer points to x 
        if (firstLetter < x.letter):
            x = x.leftAlphabet
        else:
            x = x.rightAlphabet
    # insert leaf at root when tree is empty 
    if (y == None):
        y = letterLeaf 
    # do string comparison, insert at left side of the alphabetTree 
    elif (firstLetter < x.letter):
        x.leftAlphabet = letterLeaf
    # insert at right side of the alphabetTree
    else:
        x.rightAlphabet = letterLeaf
    
    # Returns the pointer where the
    # new node is inserted
    # ? 
    return y
In [335]:
# print binary tree in 2D copied from sample program
COUNT = [10]
def print2DUtil(root, space) :

    # Base case
    if (root == None) :
        return

    # Increase distance between levels
    space += COUNT[0]

    # Process right child first
    print2DUtil(root.rightAlphabet, space)

    # Print current node after space
    # count
    print()
    for i in range(COUNT[0], space):
        print(end = " ")
    print(root.letter)

    # Process left child
    print2DUtil(root.leftAlphabet, space)

# Wrapper over print2DUtil()
def print2D(root) :
    
    # space=[0]
    # Pass initial space count as 0
    print2DUtil(root, 0)
In [336]:
# A utility function to insert a new
# Node with given key in BST
def insert(root, letter):

    # Create a new Node containing
    # the new element
    newleaf = letterLeaf(letter)

    # Pointer to start traversing from root
    # and traverses downward path to search
    # where the new node to be inserted
    x = root

    # Pointer y maintains the trailing
    # pointer of x
    y = None

    while (x != None):
        y = x
        if (letter < x.letter):
            x = x.leftAlphabet
        else:
            x = x.rightAlphabet
    
    # If the root is None i.e the tree is
    # empty. The new node is the root node
    if (y == None):
        y = newleaf

    # If the new key is less then the leaf node key
    # Assign the new node to be its left child
    elif (letter < y.letter):
        y.leftAlphabet = newleaf

    # else assign the new node its
    # right child
    else:
        y.rightAlphabet = newleaf

    # Returns the pointer where the
    # new node is inserted
    return y

# A utility function to do inorder
# traversal of BST
In [337]:
def Inorder(root) :

    if (root == None) :
        return
    else:
        Inorder(root.leftAlphabet)
        print( root.letter, end = " " )
        Inorder(root.rightAlphabet)
In [338]:
#Driver Code
import random
#if __name__ == '__main__':

alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
root = None
# pick a random letter in the alphabet
random_letter = random.choice(alphabet)
#print(random_letter)
#insert it into the tree, insert the first one 
root = insert(root, random_letter)
# remove that letter from list
alphabet.remove(random_letter)
print(alphabet)
len_list = (len(alphabet))
#print(len_list)
while len_list > 0:
    random_letter = random.choice(alphabet)
    insert(root,random_letter)
    alphabet.remove(random_letter)
    #print("inserting and removing letter {} ".format(random_letter))
    len_list -= 1
# keep inserting until the list is empty 
# print tree 
print2D(root)
# can try multiple times for different tree configurations
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

                                                  z

                                                            y

                                                                      x

                                        w

                                                  v

                                                                      u

                                                            t

                                                                                s

                                                                      r

                              q

                                                            p

                                                                      o

                                                  n

                                        m

                    l

          k

j

                              i

                    h

                                        g

                              f

          e

                                        d

                              c

                                        b

                    a
In [329]:
# print a vertical standing tree 
# https://www.geeksforgeeks.org/print-level-order-traversal-line-line/
# https://www.geeksforgeeks.org/level-order-tree-traversal/
In [323]:
# a morse code tree
# https://www.101computing.net/morse-code-using-a-binary-tree/
In [ ]:
#firstLetter = grepFirstLetter()
#print(firstLetter)