So I am having to write an insert function for a binary tree to make it a binary search tree, but I'm having some trouble. Everything is functions, so I understand that there is no concept of a state. Therefore, I need to recursively create the tree over and over when inserting. I'm having trouble wrapping my head around this idea.
treenode -> procedure(val, left, right) procedure(some) if some then -(some, 1) then right else left else val
This allows me to create nodes and access the value, the left sub-tree and right sub-tree like so (0 stands for an empty tree):
.treenode(4, 0, 0)
to create a more complex tree, I can do:
.treenode(4, .treenode(3, 0, 0), .treenode(6, .treenode(2, 0, 0), 0))
I have gotten as far as inserting into an empty tree:
insert -> procedure(root, value) if empty(root) then .treenode(value, 0, 0) else insert_recursive(root, .treenode(value, 0, 0)
This is where I cannot figure out how to insert into a tree like this. There is not concept of a state in this language so I need to somehow recursively append the new node with the value onto the current tree. If someone could give me a hint,, I would really appreciate it. The way I'm supposed to call this is:
tree = empty
tree = insert(tree, 4)
tree = insert(tree, 6)
....
and so on