[英]Printing a binary tree
I just started working with classes in Python and I am at a roadblock trying to print a binary tree that I created. 我刚刚开始使用Python编写类,遇到了一个障碍,试图打印我创建的二叉树。 Here is the code I have: 这是我的代码:
class Node(object):
def __init__(self, number):
self.number=number
self.right=None
self.lef=None
def add_node(self,number):
if number < self.number:
self.left = self.left.add_node(number)
if number > self.number:
self.right = self.right.add_node(number)
The first part represents the root of the tree and the add_node function adds a node in the tree. 第一部分代表树的根,add_node函数在树中添加一个节点。 I created a new instance for the root of the tree: 我为树的根创建了一个新实例:
Tree = Node(6) 树=节点(6)
The problem that I am facing is printing the tree. 我面临的问题是打印树。 If I just say print Tree
, I get this: 如果我只是说print Tree
,我会得到:
<__main__.Node object at 0x10f6e5210>
Somebody told me that I have to create a function to actually print the tree and this function looks like the function that's creating a new node but so far I wasn't able to do that. 有人告诉我,我必须创建一个函数才能实际打印树,该函数看起来像正在创建新节点的函数,但到目前为止我还无法做到这一点。 Any help please?! 有什么帮助吗?
You can add the __str__
method to determine how your node object reacts when used as a string, ie str(Node(6))
. 您可以添加__str__
方法来确定您的节点对象用作字符串时的反应,即str(Node(6))
。 This is useful if you want to give out a string representations in print statements etc. without calling methods directly. 如果您想在打印语句等中给出字符串表示形式而无需直接调用方法,则这很有用。
class Node(object):
def __init__(self, number):
self.number=number
self.right=None
self.lef=None
def add_node(self,number):
if number < self.number:
self.left = self.left.add_node(number)
if number > self.number:
self.right = self.right.add_node(number)
def __str__(self):
return str(self.number)
print Node(6)
Edit: 编辑:
While __str__()
returns bytes, __unicode__()
returns characters. __str__()
返回字节,而__unicode__()
返回字符。 __unicode__()
is actually supposed to replace __str__()
, so it's actually recommended to use __unicode__()
instead (in Python 2.x there's both for compatibility reasons). __unicode__()
实际上应该更换__str__()
所以它实际上是推荐使用__unicode__()
而不是(在Python 2.x的还有两对兼容性的原因)。
A 3rd way to represent your object is __repr__()
which is used for less formal string representations but rather for debugging etc. The returned string should look like a valid Python expression that could be used to recreate an object with the same value. 表示对象的第三种方法是__repr__()
,它用于非正式形式的字符串表示形式,而用于调试等。返回的字符串应看起来像一个有效的Python表达式,可用于重新创建具有相同值的对象。
For more information have a look at the language reference . 有关更多信息,请参见语言参考 。
Yes you need to add a function to create a function to print
the value at the node. 是的,您需要添加一个函数来创建一个函数以在节点上print
该值。 The function can be as simple as 该功能可以很简单
def dis(self):
print(self.number)
And you can now print using 现在您可以使用
print (Tree.disp())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.