A Binary Search Tree is a binary tree where each node contains a key and an optional associated value.
It allows particularly fast lookup, addition, and removal of items.
A new key in Binary Search Tree is always inserted at a leaf node. We start searching for the key to be inserted from the root until we hit a leaf node. Once the appropriate leaf node is found, the new node is added as a child of that leaf node.
Node
ClassTo implement a BST, the first thing you’d need is a node. A node should have a key, a left child, a right child, and constructors. This node can be implemented as a class and here is what it would like in code.
class Node {public:int key; //value of the NodeNode* left; // leftChild (will also be of the Node class)Node* right; // rightChild (will also be of the Node class)Node(int item) // Constructor to initialize a node with given value{key = item;left = NULL;right = NULL;}};
BinarySearchTree
ClassLet’s create a tree class:
class BinarySearchTree {Node* root; // The root nodepublic:BinarySearchTree(int rootValue) { // constructor to initialize Tree and the root noderoot = new Node(rootValue);}Node* getRoot() { // Getter - gets root nodereturn root;}};
We’ll be implementing Insert
and In-order
Traversal (Recursive) Functions.
Let’s put node and binary search tree classes together to implement a complete BST.
// BST Nodeclass Node {public:int key;Node* left;Node* right;// Default ConstructorNode() {key = 0;left = NULL;right = NULL;}// Parametrized ConstructorNode(int val) {key = val;left = NULL;right = NULL;}};// BST Classclass BinarySearchTree {private:Node * root;public:BinarySearchTree(int rootValue) {root=new Node(rootValue);}Node* getRoot() {return root;}// A utility function to do inorder traversal of BSTvoid inorder(Node *root) {if (root != NULL) {inorder(root->left);cout << root->key << endl;inorder(root->right);}}/* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key) {/* If the tree is empty, return a new node */if (node == NULL) return new Node(key);/* Otherwise, recur down the tree */if (key < node->key)node->left = insert(node->left, key);else if (key > node->key)node->right = insert(node->right, key);/* return the (unchanged) node pointer */return node;}};// Driver Program to test above functionsint main(){// Let's create the above Binary Search TreeBinarySearchTree BST(6);BST.insert(BST.getRoot(), 3);BST.insert(BST.getRoot(), 9);BST.insert(BST.getRoot(), 1);BST.insert(BST.getRoot(), 5);BST.insert(BST.getRoot(), 7);BST.insert(BST.getRoot(), 11);// print inoder traversal of the BSTBST.inorder(BST.getRoot());return 0;}
It completes the BST
insertion and In-Order traversal methods using recursion.
Free Resources