Dev S
Dev S

Reputation: 49

how to print a binary search tree in python?

Below is a binary search tree which has a root node, a left node and a right node. The code works but I want to display this binary search tree so that i can see every node in layer... Here is the code...

class Node:
    def __init__(self,value):
        self.value = value
        self.left = None
        self.right = None

class Binary_search_tree:
    def __init__(self):
        self.root=None

    def insert(self,value):
        if self.root==None:
            self.root=Node(value)
        else:
            self.insert_after_root(value)

    def insert_after_root(self, value):
        if value > self.root.value:
            self.root.left = Node(value)
        elif value < self.root.value:
            self.root.right = Node(value)

bst = Binary_search_tree()
bst.insert(4)
bst.insert_after_root(2)
bst.insert_after_root(8)

Upvotes: 2

Views: 3490

Answers (2)

just-Luka
just-Luka

Reputation: 407

Here is a simple implementation of binary search tree. In addition I recommend you to don't use == operator with None, instead of that use is, here why should I avoid == None

class Node: 
    def __init__(self,key): 
        self.left = None
        self.right = None
        self.value = key 


def insert(root,node): 
    if root is None: 
        root = node 
    else: 
        if root.value < node.value: 
            if root.right is None: 
                root.right = node 
            else: 
                insert(root.right, node) 
        else: 
            if root.left is None: 
                root.left = node 
            else: 
                insert(root.left, node) 


def left_right(root): 
    if root: 
        left_right(root.left) 
        print(root.value)  # that shows your tree
        left_right(root.right) 
        

tree = Node(20) 
insert(tree,Node(30)) 
insert(tree,Node(10)) 
insert(tree,Node(40)) 
insert(tree,Node(90))

left_right(tree) 

Upvotes: 1

trincot
trincot

Reputation: 350272

Your implementation has some problems:

  • The tree can only have 3 nodes, since you never create a grand-child of the root, but always make the new node either the root, or one of its children

  • left/right are reversed: you should insert smaller values to the left.

  • In the main program code, you should only use the insert method, never the insert_after_root.

Here is a correction of your implementation, based on recursion (putting a method on the Node), and an additional set of methods for producing a string representation, 90° tilted (with the root displayed at the left).

class Node:
    def __init__(self,value):
        self.value = value
        self.left = None
        self.right = None

    def insert_after(self, value):
        if value < self.value:
            if self.left:
                self.left.insert_after(value)
            else:
                self.left = Node(value)
        elif value > self.value:
            if self.right:
                self.right.insert_after(value)
            else:
                self.right = Node(value)
        else:
            raise ValueError("this tree doesn't accept duplicates")

    def __repr__(self):
        lines = []
        if self.right:
            found = False
            for line in repr(self.right).split("\n"):
                if line[0] != " ":
                    found = True
                    line = " ┌─" + line
                elif found:
                    line = " | " + line
                else:
                    line = "   " + line
                lines.append(line)
        lines.append(str(self.value))
        if self.left:
            found = False
            for line in repr(self.left).split("\n"):
                if line[0] != " ":
                    found = True
                    line = " └─" + line
                elif found:
                    line = "   " + line
                else:
                    line = " | " + line
                lines.append(line)
        return "\n".join(lines)


class Binary_search_tree:
    def __init__(self):
        self.root=None

    def insert(self,value):
        if self.root==None:
            self.root=Node(value)
        else:
            self.root.insert_after(value)

    def __repr__(self):
        return repr(self.root)

bst = Binary_search_tree()
bst.insert(4)
bst.insert(2)
bst.insert(8)
bst.insert(3)
bst.insert(5)
bst.insert(7)
bst.insert(10)

print(str(bst))

Upvotes: 5

Related Questions