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
return
in return self.leftChild.inorder()
ends the call to inorder
before self
and self.rightChild
can be handled. Remove the return
s, the method doesn't return anything anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.