I want to "walk" though a binary tree, depending on user input.
e.g., if answer no then move one node down to the left.
If yes move one node down to the right. Kinda like a 20 questions game
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
#compare if left none insert, otherwiese rigt
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
How to move around
def move(text):
if text == 'y':
print('move right')
else:
print('move left')
def menu(choices):
ans = 'NONE'
for i in theNodes:
text = input("Please select y xor n: ")
move(text)
ans = i
print(ans)
if ans in endNode:
break
print('You position ' + ans)
theNodes = ['A','B','C','D','E' ,'F', 'G']
endNode = 'EDFG'
How can you move around a tree structure, one node at a time?