python - Something about using inorder traversal prints all the items in the Binary tree -
we don't know how print in traversal order , don't know how print out result if enter binary_str, can us?
class treenode: def __init__(self , item , left , right): self.item = item self.right = right self.left = left class binarytree: def __init__(self): self.root = none def add(self , item , binary_str): binary_str_itr = iter(binary_str) self.root = self.add_aux(self.root , item , binary_str_itr) def add_aux(self , current , item , binary_str_itr): if current none: current = treenode(none , none , none) try: bit = next(binary_str_itr) if bit == '0': current.left = self.add_aux(current.left , item , binary_str_itr) elif bit == '1': current.right = self.add_aux(current.right , item , binary_str_itr) except stopiteration: current.item = item return current def print_inorder(self): self.print_inorder_aux(self.root) def print_inorder_aux(self,current): if current not none: #if not base case self.print_inorder_aux(current.left) print(current) self.print_inorder_aux(current.right)
for inoder traversal, thumb rule
leftchild - root - rightchild
follow on below link for better understanding
Comments
Post a Comment