Insert Values in a Binary Search Tree
This lesson will help you learn recursion through trees.
What is a Binary Search Tree?
A Binary Search Tree (BST) is a hierarchical data structure that consists of vertices connected through edges. The value of the left node is less than the parent node, and the value of the right node is greater than the parent node.
Code Implementation
Below is the code implementation for
Press + to interact
#include <iostream>using namespace std;// Defining the TreeNode structurestruct TreeNode{int value;TreeNode *left;TreeNode *right;};// function just to make new Tree Node and allocate memory to itTreeNode* newTreeNode(int data){TreeNode* temp = new TreeNode;temp->value = data;temp->left = NULL;temp->right = NULL;return temp;}//insert a Node in the Treevoid insert(TreeNode* &root, int data){//base case// inserts at a root if it is nullif (root == NULL){root = newTreeNode(data);return;}// first recursive case//inserts recusrively to the left side of the node after comparing valuesif (data<root->value){insert(root->left,data);}// second recursive cae//inserts recusrively to the right side of the node after comparing valueselse{insert(root->right, data);}}// printing of tree using inorder traversalvoid inorder(TreeNode* root){if (root == NULL){return;}inorder(root->left);cout << root->value << " ";inorder(root->right);}// main functionint main(){TreeNode* root = NULL;insert(root,6);insert(root,4);insert(root,8);insert(root,2);insert(root,5);inorder(root);return 0;}
Understanding the Code
In the code above, the function insert
is a recursive function as it makes a recursive call. Below is an explanation of the above code:
Driver Function
-
In the
main()
...