2

I have a python script that generate a binary tree for a given mathematical expression. I'm trying to write a function to print the binary tree if I traverse it in the level-order.

e.g. if the function is ((2+3) - 4) the output should be

   -
  / \
 +   4
/ \
2  3

output: 
-
+ 4
2 3

Code to convert the mathematical expression into a binary tree

from pythonds.basic.stack import Stack
from pythonds.trees.binaryTree 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
        return eTree

I'm using the standard pseudo-code for the breadth-first search.

printTree(Node root)

   if(root == NULL) return

   else
      create a queue 'q'
      q.enqueue(root)

      while(q is not empty)
           root = q.dequeue
           print(root)

           if(leftChild != NULL)
              q.enqueue(leftChild)
           if(rightChild != NULL)
              q.enqueue(rightChild)

Following is the python code I wrote to print the tree in level-order.

import sys

class Node:
    def __init__(self, data):
        self.data = data
        self.leftChild = None
        self.rightChid = None


class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self,item):
        self.items.insert(0, item)

    def dequeue(self):
        self.items.pop()

def printNodesInLevels(root):
    if root is None:
        return
    else:
        q = Queue()
        q.enqueue(root)

        while(q is not None):
            root = q.dequeue()
            print(root.getRootVal())

            if(root.leftChild is not None):
                q.enqueue(root.leftChild)

            if(root.rightChild is not None):
                q.enqueue(root.rightChild)

This is how I invoke the function.

pt = buildParseTree("( ( 2 + 3 ) - 4 )")
printNodesInLevels(pt)

Following is the error message I'm getting. I think I'm not passing the root of the tree to the print function properly.

None

Traceback (most recent call last): File "C:/Users/YASODA/PycharmProjects/HelloWorld/BinaryTree.py", line 77, in printNodesInLevels(pt) File "C:/Users/YASODA/PycharmProjects/HelloWorld/BinaryTree.py", line 67, in printNodesInLevels if(root.leftChild is not None): AttributeError: 'NoneType' object has no attribute 'leftChild'

5
  • 1
    Did you double check what is inside pt? Commented Feb 14, 2018 at 15:33
  • Do you mean whether pt encodes the tree correctly? Yes it does. pt.inorder() will print the tree in inorder Commented Feb 14, 2018 at 15:38
  • Ok also I do not see root.getRootVal() appear anywhere in code, only in your error message Commented Feb 14, 2018 at 15:51
  • @Skyler sorry. I pasted the wrong error message. Now I updated the question. Commented Feb 14, 2018 at 15:59
  • posted an answer, check and let me know Commented Feb 14, 2018 at 16:24

1 Answer 1

2

There are two mistakes in your code. The first one is, you need to return in dequeue,

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self,item):
        self.items.insert(0, item)

    def dequeue(self):
        return self.items.pop()

Second one is in the while loop check if the queue is empty,

while(not q.isEmpty()):
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Thank you @Skyler. However it prints the object reference instead of the value <pythonds.trees.binaryTree.BinaryTree object at 0x022827F0>. DO I have to change my Node constructor to get the node value?
Actually I sorted it out. Thank you. I just had to print(root.getRootVal()) and pass the tree to the method instead of the root value. So it should be printNodesInLevels(pt)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.