Expanding Branches
When inserting a node, remember this rule: nodes will only be added as leaves in the tree. Let’s assume we have the following tree.
If we look at this tree, you’ll notice that at each node, values in the left subtree are smaller than the value of the node, and values in the right subtree are larger than the node’s value.
Let’s say we wanted to insert the value 35. Can you predict where it would be in the tree? Let’s walk through it and see where it ends up.
We start by comparing 35 to the root node’s value, 20. Since 35 is larger than the value at the root node, we move into the right subtree.
Next, we compare 35 to 40. Since 35 is less than 40, we move into its left subtree.
Next, we compare 35 to 33. Since 35 is greater than 33, we attempt to move into node 33’s right subtree.
Since there is no right subtree at node 33, we insert node 35 there.
Pretty simple logic to walk through. That’s really it as far as node insertion goes. Try not to overcomplicate it and you’ll quickly realize that most algorithms are simple.