Therefore, I need to insert the node into the binary search tree. In my introductory class, binary search trees are represented as linked lists, such as,
[4, [5, [0, [],[]], [2, [], []]], [1, [],[]]]for this binary tree in the image below:
.
(This is not a binary search tree, just a binary tree on which I had a photo).
So, to insert node into the tree, I wrote the following recursive code:
def tree_node(key):
return [key, [],[]]
def insert(bst,key):
if bst == []:
return tree_node(key)
if key < bst[0]:
return insert(bst[1],key)
else:
return insert(bst[2],key)
return bst
It just returns node, but not a new tree with node
For instance:
>>> insert([2, [1, [], []], [3, [], []]], 6)
[6, [], []]
when it should be:
>>> insert([2, [1, [], []], [3, [], []]], 6)
[2, [1, [], []], [3, [], [6, [], []]]]
Thank!