在python二进制树中打印节点期间出错

时间:2019-03-15 13:53:58

标签: python python-3.x binary-tree

当我运行该程序时,由于存在节点 left_left_right_node =(6) right_right_left_left_left_node =(31),会产生两个相同的错误。当我调用打印树print(m_tree.print_values(root))的函数时,会出现 Traceback(最近一次调用最后一次):,其中包含行self.print_values(root.left)self.print_values(root.right)。我该如何解决这个问题?

class Tree:
    def __init__(self, root=None):
        self.root = root

    def print_values(self, root):
        if root != None:
            print(root.data)
            self.print_values(root.left)
            self.print_values(root.right)


class Node:
    def __init__(self, data=0, left=None, right=None):
        self.data = data
        self.left=left
        self.right=right

#Create a root node
root = Node(0)

#Create a tree with the root node
m_tree = Tree(root)


#Add a left and right node to the root
left_node = Node(3)
right_node = Node(4)
root.left = left_node
root.right = right_node

# Add left and right nodes that are present in subtree blow root.left and root.right nodes
left_left_node = Node (5)
left_left_left_node = Node (7)
left_left_right_node = (6)
right_right_node = Node (20)
right_right_left_node = Node (30)
right_right_right_node = Node (35)
right_right_right_right_node = Node (47)
right_right_left_left_node = (31)

root.left.left = left_left_node
root.right.right = right_right_node
root.left.left.left = left_left_left_node
root.left.left.right = left_left_right_node
root.right.right.left = right_right_left_node
root.right.right.right = right_right_right_node
root.right.right.right.right = right_right_right_right_node
root.right.right.left.left = right_right_left_left_node

print(m_tree.print_values(root))

此树的形式应为:

                                                  0
                                                /    \
                                               /      \
                                             3          4
                                            /            \
                                           5              20
                                        /    \          /    \
                                       7      6        30     35
                                                      /         \
                                                    31           47   

1 个答案:

答案 0 :(得分:2)

left_left_right_node = (6)
right_right_left_left_node = (31)

节点必须是节点对象,而不是整数。

left_left_right_node = Node(6)
right_right_left_left_node = Node(31)