Example #1
0
def buildParseTree(expression):
    expList = expression.split()
    empTree = BinaryTree('')
    parentStack = Stack()
    parentStack.push(empTree)
    currentNode = empTree

    for item in expList:
        if item == '(':
            currentNode.insertLeft('')
            parentStack.push(currentNode)
            currentNode = currentNode.getLeftChild()
        elif item not in ['+', '-', '*', '/', ')']:
            currentNode.setRootValue(int(item))
            currentNode = parentStack.pop()
        elif item in ['+', '-', '*', '/']:
            currentNode.setRootValue(item)
            currentNode.insertRight('')
            parentStack.push(currentNode)
            currentNode = currentNode.getRightChild()
        elif item == ')':
            currentNode = parentStack.pop()
        else:
            raise ValueError
    return empTree
Example #2
0
def iterInOrder(currentTree):
    pStack = Stack()
    print "\nPrinting in order traversal\n"
    while currentTree != None or not pStack.isEmpty():
        if currentTree !=None:
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        else:
            currentTree = pStack.pop()
            print currentTree.getRootValue()
            currentTree = currentTree.getRightChild()