Reputation: 23
def build_bst(l):
if len(l) == 1:
return l
mid = len(l) // 2
return bst = {'data': l[mid]}, bst["left_child"] == {'data': build_bst(l[:mid])}, bst["right_child"] == {'data': build_bst(l[(mid+1):])}
sorted_list = [12, 13, 14, 15, 16]
binary_search_tree = build_bst(sorted_list)
print(binary_search_tree)
Error:
File "recursion.py", line 6
return bst = {'data': l[mid]}, bst["left_child"] == {'data': build_bst(l[:mid])}, bst["right_child"] ==
{'data': build_bst(l[(mid+1):])}
^
SyntaxError: invalid syntax
Can someone explain what is wrong with my code, I can't seem to find the mistake.
Upvotes: 1
Views: 61
Reputation: 351228
The main issues are:
=
in a return statement -- this is what the error message is about; You should first perform the assignments in separate statements, and then perform the return
. Or, use one dictionary literal without any variable assignment.Here is a corrected version:
def build_bst(l):
if not l:
return None
mid = len(l) // 2
return {
"data": l[mid],
"left_child": build_bst(l[:mid]),
"right_child": build_bst(l[(mid+1):])
}
Upvotes: 1