2

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)
Dev S
  • 49
  • 1
  • 5
  • There are lots of implementation on the internet... did you research this question before asking? It you had a go at it, and it didn't work, then please ask a question about your implementation, sharing the code, and where you are stuck. – trincot Jun 16 '20 at 10:44
  • you can use tree traversal algorithms `inoredr(), preorder(), postorder() and levelorder()` any one of this will work – deadshot Jun 16 '20 at 10:44
  • Did you also realise your implementation cannot have more than 3 nodes? It will *replace* nodes... – trincot Jun 16 '20 at 10:46
  • this may help https://towardsdatascience.com/4-types-of-tree-traversal-algorithms-d56328450846 – deadshot Jun 16 '20 at 10:47
  • thank you so much for your kind reply sir!! – Dev S Jun 16 '20 at 10:48

2 Answers2

5

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))
trincot
  • 317,000
  • 35
  • 244
  • 286
1

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) 

just-Luka
  • 377
  • 1
  • 6
  • 19