向树中添加空值的二叉树遍历

2024-04-26 15:12:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试以前序、中序和后序递归遍历二叉树。我必须返回一个指定遍历的列表,预序遍历的代码如下:

class EmptyValue:
    pass


class BinaryTree:
    """Binary Tree class.

    Attributes:
    - root (object): the item stored at the root, or EmptyValue
    - left (BinaryTree): the left subtree of this binary tree
    - right (BinaryTree): the right subtree of this binary tree
    """

    def __init__(self, root=EmptyValue):
        """ (BinaryTree, object) -> NoneType

        Create a new binary tree with a given root value,
        and no left or right subtrees.
        """
        self.root = root    # root value
        if self.is_empty():
            # Set left and right to nothing,
            # because this is an empty binary tree.
            self.left = None
            self.right = None
        else:
            # Set left and right to be new empty trees.
            # Note that this is different than setting them to None!
            self.left = BinaryTree()
            self.right = BinaryTree()

    def is_empty(self):
        """ (BinaryTree) -> bool
        Return True if self is empty.
        Note that only empty binary trees can have left and right
        attributes set to None.
        """
        return self.root is EmptyValue

    def preorder(self):
        """ (BinaryTree) -> list
        Return a list of the items in this tree using a *preorder* traversal.
        """

        pre_order_list = []

        if self.root is None:
            pass


        if self.root != None:

            pre_order_list.append(self.root)


        if self.left and self.right:

            return pre_order_list + (self.left.preorder()) +  self.right.preorder()

        else:
            pass



        return pre_order_list  

在命令提示符中输入以下命令

tree1 = BinaryTree(1)
tree2 = BinaryTree(2)
tree3 = BinaryTree(3)
tree4 = BinaryTree(4)
tree5 = BinaryTree(5)
tree6 = BinaryTree(6)
tree1.left = tree2
tree1.right = tree3
tree2.left = tree4
tree2.right = tree5
tree3.left = tree6
tree1.preorder()  

但是由于tree3.right是None,我得到了这个错误:

[1, 2, 4, <class '__main__.EmptyValue'>, <class '__main__.EmptyValue'>, 5, <class '__main__.EmptyValue'>, <class '__main__.EmptyValue'>, 3, 6, <class '__main__.EmptyValue'>, <class '__main__.EmptyValue'>, <class '__main__.EmptyValue'>]

我不希望"<class '__main__.EmptyValue'> "在列表中,我似乎不知道如何忽略空值或基本上没有值的项。你知道吗


Tags: theselfrightnoneismainrootthis