Hi people
I am currently working to traverse a tree and do an inorder printing of the tree. Problem is my instructor wants parenthesis around the expressions not the individual numbers.

def printexp(tree):
    sVal=""
    if tree:
        sVal='( ' + printexp(tree.getLeft())
        sVal=sVal+str(tree.getRootValue())
        sVal= sVal+printexp(tree.getRight()) +' )'
    return sVal

That is the current code I have. Any ideas on how to have the parenthesis only on the expressions?

You must test wether the tree is a single value or not

def printexp(tree):
    left, right = tree.getLeft(), tree.getRight()
    sRoot = str(tree.getRootValue())
    if left or right:
        assert left and right
        return "(%s %s %s)" % (printexp(left), sRoot, printexp(right))
    else:
        return sRoot

Gribouillis: Good point, the assert at line 5, instead of putting it in if, to spot the malformed tree!

Dear Gribouillis,
I tried your code. But the assert statement only tests if the node is a leaf or not. If the node is not a leaf, then AssertionException pops up.

def printexp(tree):
        
        
    if tree:
        printexp(tree.getLeft())
        if tree.getLeft()==None:
            print '( ',
        print str(tree.getRootValue()),
        printexp(tree.getRight())
        if tree.getRight()==None:
            print ' )'

Here is what I obtained currently.
calling the methods
r=buildParseTree( ' 3 + 4 ')
>>> printexp(r)
( + ( 4 )
after I initialize the parseTree, printexp method now does not print the 3. What happened?

3 is not printed only right at line 8. Are you sure you built leaf node for 3? Put print after creation of rootvalue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.