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

时间:2014-10-26 04:50:18

标签: python tree binary-tree tree-traversal

我试图按顺序递归遍历二叉树,按顺序和后序。我必须返回指定遍历的列表,前序遍历的代码如下:

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'> "出现在列表中,我似乎无法弄清楚如何忽略空值或基本为无的项目。

0 个答案:

没有答案