Batool
Batool

Reputation: 1007

Printing binary search tree nodes using inorder traversal (recursion) in Python

I am trying to implement a simple inorder traversal method on a binary search tree.

            10
          /    \
         5      15
          \
           8

I want to print the whole tree but I am only getting the first 3 nodes printed. My questions are:

-- How can I fix my 'inorder' print method? 'insert' method works fine. -- What is the base condition in the inorder method? How will it know to stop when all the nodes have been printed?

 class Tree:
  def __init__(self, value):
    self.node = value
    self.leftChild = None
    self.rightChild  = None

  def insert(self, value):
    if self.node is None:
        self.node = value
        return True
    if self.node is not value:
        if self.node > value:
            if self.leftChild  is None:
                self.leftChild  = Tree(value)
            else:
                return self.leftChild.insert(value)
        if self.node < value:
            if self.rightChild  is None:
                self.rightChild  = Tree(value)
            else:
                 return self.rightChild.insert(value)
    else:
        return False

  def inorder(self):
      if self:  
          if self.leftChild:
              return self.leftChild.inorder()
          print self.node
          if self.rightChild:
              return self.rightChild.inorder()


tree = Tree(10)
tree.insert(5)
tree.insert(8)
tree.insert(15)
tree.inorder()


> 5
  8
  10

Upvotes: 0

Views: 2181

Answers (1)

Alex Hall
Alex Hall

Reputation: 36033

return in return self.leftChild.inorder() ends the call to inorder before self and self.rightChild can be handled. Remove the returns, the method doesn't return anything anyway.

Upvotes: 4

Related Questions