sw123456
sw123456

Reputation: 3459

Python Binary Tree Implementation insert method: help required

I am trying to create a python binary tree implementation. I believe that I have created the insert method correctly but I am having issues printing the tree using inorder traversal.

I am struggling to work out how to print each instance of the binary tree correctly. This is what I have so far. Any help would be appreciated. Thank you.

class BinaryTree():

    def __init__(self,rootid):
      self.left = None
      self.right = None
      self.rootid = rootid

    def insert(self, item):
        if item < self.rootid:
            if self.left is None:
                self.left = BinaryTree(item)
            else:
                self.left.insert(item)
        else:
            if self.right is None:
                self.right = BinaryTree(item)
            else:
                self.right.insert(item)

    def inorder_print(self):
        if self.left:
            print(self.left)
        print (self.rootid)
        if self.right:
            print(self.right)


tree = BinaryTree(5)

while True:
    answer = input("Do you wish to add a value to the tree? ")
    if answer == "y":
        item = int(input("Please enter your number: "))
        tree.insert(item)
    else:
        break

tree.inorder_print()

Upvotes: 2

Views: 347

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90899

Your inorder print function seems to be wrong.

For inorder print you need to recursive call inorder_print() for left tree, and then print the current root and then do same recursion for right tree.

Example -

def inorder_print(self):
    if self.left:
        self.left.inorder_print()
    print (self.rootid)
    if self.right:
        self.right.inorder_print()

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599610

Looks like inorder_print needs to be a recursive function: it needs to descend through its children and print each one. So instead of just doing print(self.left), you need to call self.left.inorder_print().

Upvotes: 3

Related Questions