Skip to content

Commit 4fe88f2

Browse files
committed
Added feature for negative number input
1 parent c5fbb3e commit 4fe88f2

File tree

1 file changed

+26
-26
lines changed

1 file changed

+26
-26
lines changed

traverals/binary_tree_traversals.py

+26-26
Original file line numberDiff line numberDiff line change
@@ -13,37 +13,37 @@ def __init__(self, data):
1313

1414

1515
def build_tree():
16+
print("\n********Press N to stop entering at any point of time********\n")
1617
print("Enter the value of the root node: ", end="")
17-
data = eval(input())
18-
if data < 0:
19-
return None
20-
else:
21-
q = queue.Queue()
22-
tree_node = TreeNode(data)
23-
q.put(tree_node)
24-
while not q.empty():
25-
node_found = q.get()
26-
print("Enter the left node of %s: " % node_found.data, end="")
27-
left_data = eval(input())
28-
if left_data < 0:
29-
return tree_node
30-
elif left_data >= 0:
31-
left_node = TreeNode(left_data)
32-
node_found.left = left_node
33-
q.put(left_node)
34-
print("Enter the right node of %s: " % node_found.data, end="")
35-
right_data = eval(input())
36-
if right_data < 0:
37-
return tree_node
38-
elif right_data >= 0:
39-
right_node = TreeNode(right_data)
40-
node_found.right = right_node
41-
q.put(right_node)
18+
check=input()
19+
if check=='N' or check=='n':
20+
return None
21+
data=int(check)
22+
q = queue.Queue()
23+
tree_node = TreeNode(data)
24+
q.put(tree_node)
25+
while not q.empty():
26+
node_found = q.get()
27+
print("Enter the left node of %s: " % node_found.data, end="")
28+
check=input()
29+
if check=='N' or check =='n':
30+
return tree_node
31+
left_data = int(check)
32+
left_node = TreeNode(left_data)
33+
node_found.left = left_node
34+
q.put(left_node)
35+
print("Enter the right node of %s: " % node_found.data, end="")
36+
check = input()
37+
if check == 'N' or check == 'n':
38+
return tree_node
39+
right_data = int(check)
40+
right_node = TreeNode(right_data)
41+
node_found.right = right_node
42+
q.put(right_node)
4243

4344

4445
def pre_order(node):
4546
if not isinstance(node, TreeNode) or not node:
46-
#print("Invalid input")
4747
return
4848
print(node.data, end=" ")
4949
pre_order(node.left)

0 commit comments

Comments
 (0)