class Tree:
class Node:
def __init__(self, left=None, right=None, parent=None, element=None):
self.left = left
self.right = right
self.parent = parent
self.element = element
class Position:
def make_position(self, node):
def __init__(self):
"""Create an initially empty binary tree."""
self.root = None
self.size = 0
def root(self):
"""Return the root Position of the tree( or None if tree is empty)."""
return self.make_position(self.root)
def add_root(self, e):
"""Place element e at the root of an empty tree and return new Position.
Raise ValueError if tree nonempty."""
if self.root is not None:
raise ValueError("Root Exist")
self.size = 1
self.root = self.Node(e)
return self.make_position(self.root)
我是python和python数据结构的初学者。如何在文件.py的末尾调用add_root方法并打印此方法以查看根节点中的元素?我试着写
root = Tree.Position()
print(root.make_position(root))
root = Tree.Position.make_position()
print(root.make_position(root))
但是解释器返回一个AttributeError
在其他类中定义类并不常见。我建议单独定义树,节点和位置,然后在需要它们的类中包含这些对象。此外,在其他函数中定义函数没有多大意义。功能应该彼此独立地定义。像这样的东西:
class Tree:
def __init__(self, root=None):
self.root = root
def print_values(self, root):
if root == None:
return
self.print_values(self.root.left)
print root.data
self.print_values(self.root.right)
#Define other tree operations that you want to perform here
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
m_tree.print_values(m_tree.root)