简体   繁体   中英

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. 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. I created a new instance for the root of the tree:

Tree = Node(6)

The problem that I am facing is printing the tree. If I just say print Tree , I get this:

<__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)) . 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. __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).

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.

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. The function can be as simple as

def dis(self):
    print(self.number)

And you can now print using

print (Tree.disp())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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