请帮我理解Python中的树。这是我在Internet上找到的树实现的一个例子。
from collections import deque
class EmptyTree(object):
"""Represents an empty tree."""
# Supported methods
def isEmpty(self):
return True
def __str__(self):
return ""
def __iter__(self):
"""Iterator for the tree."""
return iter([])
def preorder(self, lyst):
return
def inorder(self, lyst):
return
def postorder(self, lyst):
return
class BinaryTree(object):
"""Represents a nonempty binary tree."""
# Singleton for all empty tree objects
THE_EMPTY_TREE = EmptyTree()
def __init__(self, item):
"""Creates a tree with
the given item at the root."""
self._root = item
self._left = BinaryTree.THE_EMPTY_TREE
self._right = BinaryTree.THE_EMPTY_TREE
def isEmpty(self):
return False
def getRoot(self):
return self._root
def getLeft(self):
return self._left
def getRight(self):
return self._right
def setRoot(self, item):
self._root = item
def setLeft(self, tree):
self._left = tree
def setRight(self, tree):
self._right = tree
def removeLeft(self):
left = self._left
self._left = BinaryTree.THE_EMPTY_TREE
return left
def removeRight(self):
right = self._right
self._right = BinaryTree.THE_EMPTY_TREE
return right
def __str__(self):
"""Returns a string representation of the tree
rotated 90 degrees to the left."""
def strHelper(tree, level):
result = ""
if not tree.isEmpty():
result += strHelper(tree.getRight(), level + 1)
result += " " * level
result += str(tree.getRoot()) + "\n"
result += strHelper(tree.getLeft(), level + 1)
return result
return strHelper(self, 0)
def __iter__(self):
"""Iterator for the tree."""
lyst = []
self.inorder(lyst)
return iter(lyst)
def preorder(self, lyst):
"""Adds items to lyst during
a preorder traversal."""
lyst.append(self.getRoot())
self.getLeft().preorder(lyst)
self.getRight().preorder(lyst)
def inorder(self, lyst):
"""Adds items to lyst during
an inorder traversal."""
self.getLeft().inorder(lyst)
lyst.append(self.getRoot())
self.getRight().inorder(lyst)
def postorder(self, lyst):
"""Adds items to lystduring
a postorder traversal."""
self.getLeft().postorder(lyst)
self.getRight().postorder(lyst)
lyst.append(self.getRoot())
def levelorder(self, lyst):
"""Adds items to lyst during
a levelorder traversal."""
# levelsQueue = LinkedQueue()
levelsQueue = deque ([])
levelsQueue.append(self)
while levelsQueue != deque():
node = levelsQueue.popleft()
lyst.append(node.getRoot())
left = node.getLeft()
right = node.getRight()
if not left.isEmpty():
levelsQueue.append(left)
if not right.isEmpty():
levelsQueue.append(right)
这是制作小树的程序。
"""
File: testbinarytree.py
Builds a full binary tree with 7 nodes.
"""
from binarytree import BinaryTree
lst = ["5", "+", "2"]
for i in range(len(lst)):
b = BinaryTree(lst[0])
d = BinaryTree(lst[1])
f = BinaryTree(lst[2])
# Build the tree from the bottom up, where
# d is the root node of the entire tree
d.setLeft(b)
d.setRight(f)
def size(tree):
if tree.isEmpty():
return 0
else:
return 1 + size(tree.getLeft()) + size(tree.getRight())
def frontier(tree):
"""Returns a list containing the leaf nodes
of tree."""
if tree.isEmpty():
return []
elif tree.getLeft().isEmpty() and tree.getRight().isEmpty():
return [tree.getRoot()]
else:
return frontier(tree.getLeft()) + frontier(tree.getRight())
print ("Size:", size(d))
print ("String:")
print (d)
如何创建一个计算表达式值的类,使得答案= 7(5 + 2)。我真的想通过一个小例子来理解这个概念。
答案 0 :(得分:1)
听起来你的问题不是树,它是一个更通用(和简单)的概念,而是如何正确填充和/或评估表达式树。
如果您在修复后的订单中指定了运算符,则会变得更容易。
见this wikipedia article on how to deal with infix notation when parsing input to a desktop calculator。它被称为分流码算法。
答案 1 :(得分:0)
您应该执行以深度优先顺序遍历树的函数,计算每个节点的值,或者只是获取它的值(例如,如果它是“5”),或者进行计算(如果它是“+”示例) - 通过首先按顺序遍历树,您确定在计算该节点时将计算给定节点的所有子节点(例如,当计算“+”时将计算“5”和“2”)
然后,在树的根部,你将得到整棵树的结果。
答案 2 :(得分:0)
首先,如果这是家庭作业,我不打算提供太多细节,听起来有点像。
您的树类需要一个方法来评估树。我想它会假设每个树节点的“根”值是一个数字(当节点是叶子时,即没有子节点时)或运算符的名称(当节点有子节点时)。
您的方法将是递归的:具有子节点的树节点的值由(1)其左子树的值,(2)其右子树的值,以及(3)其中的运算符确定根”。
您可能想要一个表 - 可能需要存储在dict
- 映射运算符名称中,如"+"
到operator.add
等实际函数(或者,如果您愿意,{{ 1}})。