简体   繁体   中英

Binary Search Tree inserting character

It is possible to print character instead of integer in binary search tree? I'm trying to print letters instead of numbers. Is there's a way to make 1,2,3,4,5,6, and 7 into a,b,c,d,e,f, and g? Please help me convert int into a string or character. Thank you in advance!

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def printInorder(root):

    if root:

        printInorder(root.left)

        print(root.val),

        printInorder(root.right)


def printPostorder(root):

    if root:

        printPostorder(root.left)

        printPostorder(root.right)

        print(root.val),

 def printPreorder(root):

    if root:

        print(root.val),

        printPreorder(root.left)

        printPreorder(root.right)

root = Node(1)
root.right = Node(2)
root.right.right = Node(3)
root.right.right.right = Node(4)
root.right.right.right.right = Node(5)
root.right.right.right.right.right = Node(6)
root.right.right.right.right.right.right = Node(7)

print ("Preorder")
printPreorder(root) 
print ("In-order")
printInorder(root)
print ("Post-order")
printPostorder(root)

Most straightfoward way i can think of is to add an offset to the number then convert it to character:

def print_as_letter(num):
    ascii_a = 97
    assert num < 27, "not enough letters in the alphabet"
    letter = chr(num+ascii_a-1) # -1 since you start your nodes at 1
    print(letter)

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def printInorder(root):
    if root:
        printInorder(root.left)
        print_as_letter(root.val)
        printInorder(root.right)


def printPostorder(root):
    if root:
        printPostorder(root.left)
        printPostorder(root.right)
        print_as_letter(root.val)

def printPreorder(root):
    if root:
        print_as_letter(root.val)
        printPreorder(root.left)
        printPreorder(root.right)

root = Node(1)
root.right = Node(2)
root.right.right = Node(3)
root.right.right.right = Node(4)
root.right.right.right.right = Node(5)
root.right.right.right.right.right = Node(6)
root.right.right.right.right.right.right = Node(7)

print ("Preorder")
printPreorder(root) 
print ("In-order")
printInorder(root)
print ("Post-order")
printPostorder(root)

output:


Preorder
a
b
c
d
e
f
g
In-order
a
b
c
d
e
f
g
Post-order
g
f
e
d
c
b
a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM