Binary Search Tree Insertion (Implementation)
In this chapter, we'll study the implementation of Binary Search Tree insertion in C++ through the iterative and recursive approaches.
We'll cover the following...
Introduction #
There are two ways to code a BST insert function
- Iteratively
- Recursively
We will be implementing both in this lesson. We’ll end up with the following tree once we implement the BST insert function and insert the elements [6,4,9,5,2,8,12,10,14]
.
Insert Implementation (Iterative) #
The iterative implementation of the insertBST
function as part of the BinarySearchTree
class is as follows:
Press + to interact
void insertBST(int val) {if(getRoot()==NULL){root=new Node(val);return;}//starting from the rootNode* currentNode = root;Node* parent;//while we get to the null nodewhile (currentNode) {parent = currentNode; //update the parentif (val < currentNode->value) {//if newValue < currentNode.val,//iterate to the left subtreecurrentNode = currentNode->leftChild;} else {//if newValue >= currentNode.val,//iterate to the right subtreecurrentNode = currentNode->rightChild;}}//by now, we will have the parent of the null//node where we have to insert the newValueif (val < parent->value) {//if newValue < parent.val//insert into the leftChildparent->leftChild = new Node(val);} else {//if newValue >= parent.val//insert into the rightChildparent->rightChild = new Node(val);}}
Let’s now put this function in our class and insert some values into our ...