Added feature for negative number input

This commit is contained in:
amankumargupta 2017-06-07 23:41:44 +05:30
parent c5fbb3e772
commit 4fe88f2f8e

View File

@ -13,37 +13,37 @@ class TreeNode:
def build_tree(): def build_tree():
print("\n********Press N to stop entering at any point of time********\n")
print("Enter the value of the root node: ", end="") print("Enter the value of the root node: ", end="")
data = eval(input()) check=input()
if data < 0: if check=='N' or check=='n':
return None return None
else: data=int(check)
q = queue.Queue() q = queue.Queue()
tree_node = TreeNode(data) tree_node = TreeNode(data)
q.put(tree_node) q.put(tree_node)
while not q.empty(): while not q.empty():
node_found = q.get() node_found = q.get()
print("Enter the left node of %s: " % node_found.data, end="") print("Enter the left node of %s: " % node_found.data, end="")
left_data = eval(input()) check=input()
if left_data < 0: if check=='N' or check =='n':
return tree_node return tree_node
elif left_data >= 0: left_data = int(check)
left_node = TreeNode(left_data) left_node = TreeNode(left_data)
node_found.left = left_node node_found.left = left_node
q.put(left_node) q.put(left_node)
print("Enter the right node of %s: " % node_found.data, end="") print("Enter the right node of %s: " % node_found.data, end="")
right_data = eval(input()) check = input()
if right_data < 0: if check == 'N' or check == 'n':
return tree_node return tree_node
elif right_data >= 0: right_data = int(check)
right_node = TreeNode(right_data) right_node = TreeNode(right_data)
node_found.right = right_node node_found.right = right_node
q.put(right_node) q.put(right_node)
def pre_order(node): def pre_order(node):
if not isinstance(node, TreeNode) or not node: if not isinstance(node, TreeNode) or not node:
#print("Invalid input")
return return
print(node.data, end=" ") print(node.data, end=" ")
pre_order(node.left) pre_order(node.left)