开发者

Trees in Python

开发者 https://www.devze.com 2023-02-19 20:34 出处:网络
Please help me to understand trees in Python. This is an example of tree implementation I found in the Internet.

Please help me to understand trees in Python. This is an example of tree implementation I found in the 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()
           开发者_StackOverflow社区 right = node.getRight()
            if not left.isEmpty():
                levelsQueue.append(left)
            if not right.isEmpty():
                levelsQueue.append(right)

This is programm that makes the small tree.

"""
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)

How can I make a class that will count the value of the expression, such that the answer = 7 (5+2). I really want to understand the concept with a small example.


It sounds like your problem isn't trees, which are a much more general (and simple) concept, but in how to properly populate and/or evaluate an expression tree.

If you have your operators specified in post-fix order, it becomes a lot easier.

See this wikipedia article on how to deal with infix notation when parsing input to a desktop calculator. It is called the shunting-yard algorithm.


You should do function that walks a tree in depth first order, calculating value of each node, either just taking value of it (if it is "5" for example), or making calculation (if it is "+" for example) - by walking the tree in depth first order you are sure that all subnodes of given node will be calculated when you are calculating that node (for example "5" and "2" will be calculated when you are calculating "+").

Then, at the root of the tree you'll get the result of the whole tree.


First of all, I'm not going to give much detail in case this is homework, which it sounds a bit like.

You need a method on your tree class that evaluates the tree. I suppose it'll assume that the "root" value of each tree node is a number (when the node is a leaf, i.e. when it has no children) or the name of an operator (When the node has children).

Your method will be recursive: the value of a tree-node with children is determined by (1) the value of its left subtree, (2) the value of its right subtree, and (3) the operator in its "root".

You'll probably want a table -- maybe stored in a dict -- mapping operator names like "+" to actual functions like operator.add (or, if you prefer, lambda x,y: x+y).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号