Using a binary search tree provides a nice improvement for the put method.
For the array implementation, we have to move all larger keys, but not for the binary search tree.
The put method again searches efficiently, but it doesn't have to move any other keys.
So the code is just a small variation on the recursive code for the get method:
- If the BST is empty, just create a new Node with this key,val pair and assign this Node to root.
- else if key is smaller than root.key, the key has to be in the left subtree if it is present. So put the key,val pair in the left subtree.
- else if key is greater than root.key, the key has to be in the right subtree if it is present. So put the key,val pair in the right subtree.
- else key is equal to root.key, so replace root.val with val.
Again, the recursive code serves as an inductive proof of correctness.