When adding a value to a BST you transverse the tree until you find an empty spot for it and insert a new node at that spot.
First we start with the degenerate case. I.e., there are no nodes and the root is null / empty.
Pseudocode:
if root is null then
root = new node(value);
return;
end if
So, all we are doing here is building the root node of the tree. It contains no leaf nodes.
All subsequent inserts now require us to transverse the tree.
So first we need a starting point which will be the root node. Then we also need to know if we have reached an empty spot where we can insert our new value into the tree. This requires keeping track of two variables; one to hold the current node we are examining and one to hold the parent of that node.
Psuedocode:
# initialize tracking variables.
checkNode = root;
parentNode = checkNode;
while checkNode is null do
parent = checkNode; # want to save this for when we find a spot to store our new value
if valueOf(checkNode) equals value then return # the value is already stored
if value < valueOf(checkNode) then
# the new value is less than the value stored in this node so continue down the left branch
checkNode = checkNode.left
else
checkNode = checkNode.right # otherwise continue down the right branch
end while
# at this point checkNode will be null and parent will be set to a node that can store a new node with our value.
if value < valueOf(parent) then
parent.left = node(value) # store a new node in the left of the found parent node
else
parent.right = node(value)
What we are doing is transversing down the tree comparing the value to be added to the value of the node we are checking. We are also keeping track of the parent of the node we are checking since this is where we are going to eventually end up inserting our new node. This is because we end our search when checkNode is null.