2

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()

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.