I'm building a BST, however instead of using nodes to implement, I'm using lists.
I built it with the same logic I've used in c++ and c#, however I'm getting an incorrect output. I've racked my head against this problem for a while now, but I just don't see anything that's "wrong". I should note that tree[0] is the node value, tree[1] is for the left subtree and tree[2] is the right subtree.
def insert(tree, value):
if tree == []:
tree.append(value)
tree.append([])
tree.append([])
return 0
else:
if value == tree[0]:
return -1
elif value < tree[0]:
if tree[1] == []:
tree[1].append(value)
tree[1].append([])
tree[1].append([])
return 0
else:
insert(tree[1],value)
elif value > tree[0]:
if tree[2] == []:
tree[2].append(value)
tree[2].append([])
tree[2].append([])
return 0
else:
insert(tree[2],value)
An example list of values to pass
['20', '10', '30', '5', '35', '8', '25', '2', '37', '8', '27', '15', '22']
Expected output:
[20, [10 ,[5 ,[2 ,[] ,[]], [8, [], []]], [15, [], []]], [30, [25, [22, [], []], [27, [], []]], [35, [], [37, [], []]]]]
Actual output:
['20', ['10', [], ['2', ['15', [], []], []]], ['30', ['25', ['22', [], []], ['27', [], []]], ['5', ['35', [], ['37', [], []]], ['8', [], []]]]]
I've tried tracing it as it runs, but even that looks like it should be correct