简体   繁体   English

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

[英]Create a root node in binary tree python structure

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.我是 python 和 python 数据结构的初学者。 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?如何在文件 .py 的末尾调用 add_root 方法并打印此方法以查看根节点中的元素? I tried to write我试着写

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

but the interpreter return an AttributeError但解释器返回一个 AttributeError

It's not very typical to define classes within other classes.在其他类中定义类并不是很典型。 I would recommend defining Tree, Node, and Position separately and then including those objects within the classes that require them.我建议分别定义 Tree、Node 和 Position,然后将这些对象包含在需要它们的类中。 Also, it doesn't make much sense to define functions inside other functions.此外,在其他函数中定义函数也没有多大意义。 Functions should be defined independently from each other.函数应该相互独立地定义。 Something like this:像这样的东西:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM