How to implement binary tree using python?

Description

To implement binary tree using python3.

Root node:

  • Its act like parent for child
    node.
  • In this example tree has only
    one root node.
  • All child node has been
    associated with root node.

Inserting Node:

  •  The insert method compares the
    value of the node to the parent node
    and decides to add it as a left
    node or a right node.

#parent node

class Root:

def __init__(self, data):

self.left = None

self.right = None

self.data = data

#compare the new value with the parent node

def insert(self, data):

if self.data:

if data < self.data:

if self.left is None: self.left = Root(data)

else: self.left.insert(data) elif data > self.data:

if self.right is None:

self.right = Root(data)

else:

self.right.insert(data)

else:

self.data = data

#print the tree

def tree(self):

if self.left:

self.left.tree()

print( self.data)

if self.right:

self.right.tree()

# Use the insert method to add nodes

r = Root(13)

r.insert(23)

r.insert(3)

r.insert(15)

r.insert(16)

r.insert(4)

r.tree()

Leave Comment

Your email address will not be published. Required fields are marked *

clear formSubmit