gpt4 book ai didi

python - 在python二叉树结构中创建根节点

转载 作者:行者123 更新时间:2023-12-01 08:12:55 26 4
gpt4 key购买 nike

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)

I'am a beginner with python and python data structure. How can I call at the end of file .py the methods add_root and print this method to see the element in root node? I tried to write

root = Tree.Position()
print(root.make_position(root))
root = Tree.Position.make_position()
print(root.make_position(root))

但是解释器返回一个 AttributeError

最佳答案

在其他类中定义类并不常见。我建议单独定义 Tree、Node 和 Position,然后将这些对象包含在需要它们的类中。此外,在其他函数中定义函数也没有多大意义。函数的定义应该相互独立。像这样的事情:

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)

关于python - 在python二叉树结构中创建根节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com