3

I have a problem with the Parse Tree code. When I try to show it with post-order, it gives me an error message that should be str the parameter and not int.

from classStack import Stack
from classTree import BinaryTree

def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()

        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()

        elif i == ')':
            currentTree = pStack.pop()

        else:
            raise ValueError("No se contempla el carácter evaluado")

    return eTree

ParseTree = buildParseTree("( 8 * 5 )")
ParseTree.printPostordenTree(0)

Error:

Traceback (most recent call last):
  File "C:\Users\Franco Calvacho\Downloads\Árboles\parseTree.py", line 38, in <module>
    ParseTree.printPostordenTree(0)
  File "C:\Users\Franco Calvacho\Downloads\Árboles\classTree.py", line 62, in printPostordenTree
    self.getLeftChild().printPostordenTree(n+1)
  File "C:\Users\Franco Calvacho\Downloads\Árboles\classTree.py", line 67, in printPostordenTree
    print("Level: "+ str(n) + " " + self.getRootVal())
TypeError: must be str, not int
[Finished in 0.2s]

Here's the BinaryTree code. I make it clear that the BinaryTree code alone is OK and it doesn't give me that error message. Under that code I leave you in python comments for you to see.

class BinaryTree(object):
    def __init__(self, data): 
        self.key = data
        self.leftChild = None 
        self.rightChild = None 

    def insertLeft(self, newNode): 
        if self.leftChild == None:  
            self.leftChild = BinaryTree(newNode) 
        else: 
            t = BinaryTree(newNode) 
            t.leftChild = self.leftChild 
            self.leftChild = t 

    def insertRight(self, newNode): 
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else: 
            t = BinaryTree(newNode)
            t.rightChild = self.rightChild
            self.rightChild = t 

    def getRightChild(self):
        return self.rightChild

    def getLeftChild(self):
        return self.leftChild

    def setRootVal(self, obj): 
        self.key = obj

    def getRootVal(self):
        return self.key     

    def printPreordenTree(self, n): 
        if self.getRootVal() != None: 
            print("Level: "+ str(n) + " " + self.getRootVal())
            n+=1 

            if self.getLeftChild() != None:
                self.getLeftChild().printPreordenTree(n) 

            if self.getRightChild() != None:
                self.getRightChild().printPreordenTree(n) 
        return n 

    def printInordenTree(self, n): 
        if self.getRootVal() != None: 
            if self.getLeftChild() != None: 
                self.getLeftChild().printInordenTree(n+1) 

            print("Level: "+ str(n) + " " + self.getRootVal())
            n+=1 

            if self.getRightChild() != None: 
                self.getRightChild().printInordenTree(n) 
        return n 

    def printPostordenTree(self, n):
        if self.getRootVal() != None:
            if self.getLeftChild() != None:
                self.getLeftChild().printPostordenTree(n+1)

            if self.getRightChild() != None:
                self.getRightChild().printPostordenTree(n+1) 

            print("Level: "+ str(n) + " " + self.getRootVal())
            n+=1 
        return n 

"""a = BinaryTree("a")
a.insertLeft("b") 
a.insertRight("c") 
a.getLeftChild().insertLeft("d") 
a.getRightChild().insertLeft("e") 
a.getRightChild().insertRight("f") 
print("Imprimo el árbol de forma Preorden")
a.printPreordenTree(0)
print("\nImprimo el árbol de forma Inorden")
a.printInordenTree(0)
print("\nImprimo el árbol de forma Postorden")
a.printPostordenTree(0)"""
vaultah
  • 44,105
  • 12
  • 114
  • 143
calvin11
  • 187
  • 1
  • 17
  • 3
    Possible duplicate of [Making a string out of a string and an integer in Python](https://stackoverflow.com/questions/2823211/making-a-string-out-of-a-string-and-an-integer-in-python) – OneCricketeer Oct 19 '17 at 16:29
  • 1
    `self.getRootVal()` is probably returning an int on the offending line. – Jared Smith Oct 19 '17 at 16:58
  • `currentTree.setRootVal(int(i))` sets the root to an integer. `self.getRootVal()` returns the integer as Jared says above. The bug is probably setting it to be an integer in the first place, nodes need to be strings. – AnnanFay Oct 19 '17 at 17:06

1 Answers1

6
print("Level: "+ str(n) + " " + self.getRootVal())
TypeError: must be str, not int

This explains the error: You can only append strings to strings using the "+" operator, not integers. The first three arguments are strings, but self.getRootVal() ist not.

First possible solution: Cast it to str, like you did with n:

print("Level: "+ str(n) + " " + str(self.getRootVal()))

Or you can use format strings:

print("Level: {} {}".format(n, self.getRootVal()))

The latter does not require you to cast the arguments to strings, and may be better readable.

YSelf
  • 2,646
  • 1
  • 14
  • 19