我有python script为给定的数学表达式生成二叉树。如果我在级别顺序中遍历它,我试图写一个function to print the binary tree。
e.g。如果函数是((2 + 3) - 4),则输出应为
-
/ \
+ 4
/ \
2 3
output:
-
+ 4
2 3
将数学表达式转换为二叉树的代码
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
我使用标准伪代码进行广度优先搜索。
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)
以下是我编写的用于按级别顺序打印树的python代码。
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)
这是我调用函数的方式。
pt = buildParseTree("( ( 2 + 3 ) - 4 )")
printNodesInLevels(pt)
以下是我收到的错误消息。我想我没有正确地将树的根传递给打印功能。
无
Traceback(最近一次调用最后一次):文件 " C:/Users/YASODA/PycharmProjects/HelloWorld/BinaryTree.py" ;,第77行, 在 printNodesInLevels(pt)File" C:/Users/YASODA/PycharmProjects/HelloWorld/BinaryTree.py" ;,第67行, 在printNodesInLevels中 if(root.leftChild不是None):AttributeError:' NoneType'对象没有属性' leftChild'
答案 0 :(得分:1)
您的代码中有两个错误。第一个是,你需要以队列形式返回,
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()
第二个是在while循环中检查队列是否为空,
while(not q.isEmpty()):