Binary Search Tree Implementation C++ Runtime Error - c++

I have a problem when implementing BST in C++. When I insert a small data around 20,000 data to the BST, it runs well. If I try to insert a big number of data around 100,000. The BST get an runtime error. Can you guys help me?
This is my implementation.
Binary Search.h
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
struct treeNode
{
long long data;
treeNode *left;
treeNode *right;
};
treeNode *insertNode(treeNode *node,long long data)
{
if(node==NULL)
{
treeNode *temp = new treeNode;
//temp = (treeNode *)malloc(sizeof(treeNode));
temp -> data = data;
temp -> left = temp -> right = NULL;
return temp;
}
if(data >(node->data))
{
node->right = insertNode(node->right,data);
}
else if(data < (node->data))
{
node->left = insertNode(node->left,data);
}
/* Else there is nothing to do as the data is already in the tree. */
return node;
}
treeNode * searchNode(treeNode *node, long long data)
{
if(node==NULL)
{
/* Element is not found */
return NULL;
}
if(data > node->data)
{
/* Search in the right sub tree. */
return searchNode(node->right,data);
}
else if(data < node->data)
{
/* Search in the left sub tree. */
return searchNode(node->left,data);
}
else
{
/* Element Found */
return node;
}
}
void displayInorder(treeNode *node)
{
if(node==NULL)
{
return;
}
displayInorder(node->left);
cout<<" " << node->data<<" ";
displayInorder(node->right);
}
void displayPreorder(treeNode *node)
{
if(node==NULL)
{
return;
}
cout<<" " <<node->data<<" ";
displayPreorder(node->left);
displayPreorder(node->right);
}
void displayPostorder(treeNode *node)
{
if(node==NULL)
{
return;
}
displayPostorder(node->left);
displayPostorder(node->right);
cout<<" " <<node->data<<" ";
}
I get the run time error at :
node->right = insertNode(node->right,data);
Please do help me guys.
Thank you in advance!

You're likely running out of stack with all the recursion, so you could either increase the stack, or write some (or all) of your functions to use iteration instead of recursion (although preorder, postorder, inorder traversals are hard to write correctly as loops).
Here's a simple example for the Search and Insert methods:
struct TreeNode
{
long long data = 0;
std::shared_ptr<TreeNode> left;
std::shared_ptr<TreeNode> right;
TreeNode(long long _data) : data(_data){}
};
class BST
{
public:
void Insert(std::shared_ptr<TreeNode> node)
{
if (!node)
throw std::runtime_error("Cannot insert null node");
if (!root)
{
root = node;
return;
}
std::shared_ptr<TreeNode>* next = &root;
while(*next)
{
if (node->data < (*next)->data)
next = &((*next)->left);
else
next = &((*next)->right);
}
*next = node;
}
std::pair<bool, std::shared_ptr<TreeNode>> Search(long long data)
{
if (!root)
return std::make_pair(false, nullptr); // searching empty tree
std::shared_ptr<TreeNode> next = root;
while(next)
{
if (data < next->data)
next = next->left;
else if (data > next->data)
next = next->right;
else
return std::make_pair(true, next); // match found
}
// no match found
return std::make_pair(false, nullptr);
}
private:
std::shared_ptr<TreeNode> root;
};
A full working demo can be found here

Related

void insert(int ) method for BST tree/C++

I have been trying to get this function working for the longest time now. It is part of an assignment for an online course, but it seems no matter what I submit, the function fails for both the empty child test and the left child test. See code below. The main() function is deliberately commented out. Any info./input is much appreciated.
// C++ binary trees and stuff;
//
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
class BST
{
public:
int data;
BST *left;
BST *right;
//BST *root;
// BST() constructor
BST (int num)
{
data = num;
left = nullptr;
right = nullptr;
root = nullptr;
}
// constructors for root node(s), initializing as root when no values exist yet;
BST() : root (nullptr){}
BST (BST *rootNode) : root(rootNode){}
void insert (int value)
{
BST *newNode = new BST();
newNode = root;
if (root == nullptr)
{
root = new BST (value);
}
else
{
root->data = value;
}
// check if newNode's value equals the passed-in value:
if (value == root->data)
{
//cout << "\nWarning! Value already exists in tree, so nothing will be done.\n";
return;
}
// check if value is < or > newNode's value:
if (value <= root->data)
{
if (root->left == nullptr)
{
// make a new node as the left child of this node,
root->left = new BST(value);
}
else
{
// recursively call insert() on tree's left side,
root->left->insert(value);
}
}
else
{
if (root->right == nullptr)
{
// make a new node as the right child of this node,
root->right = new BST(value);
}
else
{
// recursively call insert() on tree's right side,
root->right->insert(value);
}
}
}
public:
BST *root;
};
/*
int main (int argc, char *argv[])
{
//...insert code here,
// create nodes,...
BST rootNode(5);
BST leftNode(4);
BST rightNode(6);
// connect the nodes to the tree via rootNode.left and rootNode.right,..
rootNode.left = &leftNode;
rootNode.right = &rightNode;
printf ("\nData (root) value = %i, rootNode.left = %i, and rootNode.right = %i\n",
rootNode.data, rootNode.left->data, rootNode.right->data);
cout << "\n\nHello, Solar System!\n";
return 0;
}
*/
Okay, here's my suggestion. You need to reformat your code. You need two classes. You need a BST, and you need a Node. The various methods to add/remove/traverse are part of the BST class. Nodes are just Nodes.
So:
class BST_Node {
public:
int value;
BST_Node * left = nullptr;
BST_Node * right = nullptr;
// Define constructors, etc.
};
class BST {
public:
BST_Node * root = nullptr;
BST_Node * insert(int value);
void insertNode(BST_Node *node);
void insertNodeBelow(BST_Node *nodeToInsert, BST_Node *startingNode);
};
BST_Node * BST::insert(int value) {
BST_Node * node = new BST_Node(value);
insertNode(node);
return node;
}
void BST::insertNode(BST_Node *node) {
if (node == nullptr) {
return;
}
if (root == nullptr) {
root = node;
}
else {
insertNodeBelow(node, root);
}
}
void BST::insertNodeBelow(BST_Node *node, BST_Node *startingNode) {
if (node == nullptr || startingNode == nullptr) {
return;
}
if (node->value < startingNode->value) {
if (startingNode->left != nullptr) {
insertNodeBelow(node, startingNode->left);
}
else {
startingNode->left = node;
}
}
else {
if (startingNode->right != nullptr) {
insertNodeBelow(node, startingNode->right);
}
else {
startingNode->right = node;
}
}
}
How this works... First, the logic of how to store nodes is in BST. Nodes don't care. Second, I made methods for either inserting a value or a node. Because I think that's handy. That should be fairly easy to understand.
The root node can be null, if so, then your inserted node is now root. Otherwise it calls the recursive insertion function. Now, you could simplify this a little, but I didn't want to get too clever.
So it's simple. We look to see where it belongs relative to the point we're at (initially the root). Either we go into the left branch or the right branch. But that branch could be empty, so you just plop it right in. If it's not empty, then you recurse.
I didn't test it.

How to implement complete binary in c++?

I want to try make insertion of complete binary tree using recursion . I make a piece of code and I cannot catch problem why value not inserted. I make height function and count nodes function with help of these function and recursive call I want to insert new node in Complete binary tree. In main get root by using get root function then send to insert function
#include<iostream>
#include<math.h>
using namespace std;
struct node{
int data;
node *left,*right;
};
class cbt{
node *root;
public:
cbt()
{
root=NULL;
}
node* get_node()
{
return root;
}
node* newNode(int key)
{
node* temp1 = new node;
temp1->data = key;
temp1->left = temp1->right = NULL;
return temp1;
}
void CBT_inseration(node* temp,int data)
{
node *ptr;
ptr=newNode(data);
if(root==NULL)
{
root=ptr;
return;
}
else
{
height = f_height(temp->left);
int excepted_node = pow(2,height)-1;
int left_tree_node_count = countNumNodes(temp->left);
int right_tree_node_count = countNumNodes(temp->right);
if(left_tree_node_count==right_tree_node_count)
{
CBT_inseration(temp->left,data);
}
else if(excepted_node != left_tree_node_count)
{
if(temp->left == NULL)
{
temp->left = ptr;
return;
}else
{
CBT_inseration(temp->left,data);
}
}
else if(temp->right == NULL)
{
temp->right=ptr;
return;
}
else if(excepted_node != left_tree_node_count)
{
if(temp->left == NULL)
{
temp->left=ptr;
return;
}
else
{
CBT_inseration(temp->right,data);
}
}
}
}
void print(node *root) {
if (root == NULL)
return;
print(root->left);
cout << root->data << " ";
print(root->right);
}
};
int main()
{
cbt obj;
node *r=NULL;
obj.CBT_inseration(obj.get_node(),4);
obj.CBT_inseration(obj.get_node(),3);
obj.CBT_inseration(obj.get_node(),5);
obj.CBT_inseration(obj.get_node(),8);
obj.print(obj.get_node());
return 0;
}
You would need to go through a debugger to see what is wrong with your code. I will tell you how I would do this:
First, you need a function to check if the tree is full. We will reuse your functions to do this:
bool isTreeFull(node* head) {
return head != NULL && countNumNodes(head) == (1 << find_height(head)) - 1;
}
Then for inserting I have to check if the number of nodes on each side are the same. This tells me that I am allowed to move one level deeper on the left side. If the number of nodes aren't the same, then I only move on to insert on the right subtree if the left subtree is full:
void CBT_inseration(int data) {
root = insert(root, data);
}
node* insert(node* head, int data) {
if (head == NULL) {
head = newNode(data);
} else {
int leftCount = countNumNodes(head->left);
int rightCount = countNumNodes(head->right);
if (leftCount == rightCount) {
head->left = insert(head->left, data);
} else {
if (isTreeFull(head->left)) {
head->right = insert(head->right, data);
} else {
head->left = insert(head->left, data);
}
}
}
return head;
}
Then you would call it like:
cbt obj;
obj.CBT_inseration(4);
obj.CBT_inseration(3);
obj.CBT_inseration(5);
obj.CBT_inseration(6);
obj.CBT_inseration(8);
obj.print(obj.get_node()); // 6 3 8 4 5

Binary Search Tree Problem with Insert Function

Hello i am new to c++ and learning about binary search trees.
I am trying to implement a simple binary search tree where i can store "KeyCodePair" object(which has string and integer) and doing some operations on tree like search and insert. Seems like there are some problems with my logic thats why first Insert function is working but second is not working(calling them from Main) I guess there is problem with the way i implemented "root" where should i write it
This is Tree.cpp:
#include "Tree.h";
#include "KeyCodePair.h";
Tree::Tree() {
treeNode* root = NULL;
}
Tree::treeNode* Tree::getNewNode(KeyCodePair data) {
treeNode* newNode = new treeNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Tree::treeNode* Tree::Insert(KeyCodePair data) {
if (root == NULL) {
root = getNewNode(data);
}
else if (data.getCode() <= root->data.getCode()) {
root->left = Insert(data);
}
else {
root->right = Insert(data);
}
return root;
}
bool Tree::Search(KeyCodePair data) {
if (root == NULL) {
return false;
}
else if (root->data.getCode() == data.getCode()) {
return true;
}
else if (data.getCode() <= root->data.getCode()) {
return Search(data);
}
else {
return Search(data);
}
}
Tree.h:
#ifndef TREE_H
#define TREE_H
#include "KeyCodePair.h"
class Tree {
private:
struct treeNode {
KeyCodePair data;
treeNode* left;
treeNode* right;
} ;
treeNode* root;
public:
treeNode* Insert( KeyCodePair data);
bool Search(KeyCodePair data);
treeNode* getNewNode(KeyCodePair data);
Tree();
};
#endif
KeyCodePair.cpp
#include "KeyCodePair.h"
KeyCodePair::KeyCodePair(string keyparam, int codeparam) {
key = keyparam;
code = codeparam;
}
KeyCodePair::KeyCodePair() {
}
string KeyCodePair::getKey() {
return key;
}
int KeyCodePair::getCode() {
return code;
}
KeyCodePair.h
#ifndef KEYCODEPAIR_H
#define KEYCODEPAIR_H
#include <iostream>
using namespace std;
class KeyCodePair {
private:
string key;
int code;
public:
KeyCodePair();
KeyCodePair(string key, int code);
string getKey();
int getCode();
};
#endif
And Finally this is the main:
#include <iostream>
#include <string>
#include "Tree.h"
#include "KeyCodePair.h"
using namespace std;
int main()
{
Tree tree = Tree();
KeyCodePair testPair = KeyCodePair("teststring1",10);
KeyCodePair qwePair = KeyCodePair("teststring2", 20);
cout << tree.Insert(testPair) << endl;
cout << tree.Insert(qwePair) << endl; // problem on second insert
if (tree.Search(testPair) == true) cout << "Found\n";
else cout << "Not Found\n";
cin.get();
return 0;
}
Let's take a look at your insert function:
Tree::treeNode* Tree::Insert(KeyCodePair data) {
if (root == NULL) {
root = getNewNode(data);
}
else if (data.getCode() <= root->data.getCode()) {
root->left = Insert(data);
}
else {
root->right = Insert(data);
}
return root;
}
What you do here is you take in the data to be inserted, and you look at the root. If there is no root, you add a new node containing the data and assign that to the root (which is why your first insert works). However, once there is a root, you then figure out if the new node should be placed to the left or right of the root, and then recursively call Insert() with the same data. This next call to Insert will do nothing different, and look at the same root of the tree over and over to most likely produce an infinite loop.
What you have to do is using your data, first traverse all the way down the tree to the position at which you want to insert your node, then insert it and assign the pointers. Some code for this might look like so:
Tree::Insert(KeyCodePair data) {
// currPos will end up being the position where we want to insert
Tree::treeNode* currPos = root;
while (currPos != NULL) {
if (data.getCode() <= currPos->data.getCode())
currPos = currPos->left;
else if (data.getCode() > currPos->data.getCode())
currPos = currPos->right;
}
// Insert at currPos and reassign the left or right pointer of
// the parent
}
The problem is that your insert only considers the root node. You need to traverse down the tree to the point where you do the insert:
class Tree {
...
public:
treeNode* Insert(KeyCodePair data);
...
};
Step 1: Change your interface
class Tree {
...
// The insert that does the work
// We pass in the current position in the tree.
treeNode* Insert(treeNode* node, KeyCodePair data);
public:
// The public interface that accepts the data and calls the internal Insert
void Insert(KeyCodePair data);
...
};
Step 2: Use the public Insert to call the internal Insert.
void Tree::Insert(KeyCodePair data) {
// Use the internal Insert() passing the root as the starting point.
// If a new value is needed it will be returned otherwise the original
// value is returned.
root = Insert(root, data);
}
Step 3: Modify the OP Insert into an Internal Insert.
Tree::treeNode* Tree::Insert(treeNode* node, KeyCodePair data) {
if (node == NULL) {
// If we have reached the tip of the tree then
// return the new node so it can be inserted.
return getNewNode(data);
}
// Otherwise we have a node so we need to find the node
// were the data will be inserted.
// so move to the next level. Assign the result as the next
// level could be null.
if (data.getCode() <= root->data.getCode()) {
node->left = Insert(node->left, data);
}
else {
node->right = Insert(node->right, data);
}
// Return this node
// So it stays in the chain.
return node;
}

Binary Search Tree Using Classes

I have been trying to implement binary search tree using classes. Every time I try to compile and run the program, the program ends. I have tried many things like making the *root public to access it in main so I can update the root, but somehow it becomes null every time.
Help will be appreciated.
This is for my university project.
#include <iostream>
using namespace std;
class tree;
class Node {
friend class tree;
private:
Node *lchild,*rchild;
int data;
public:
Node (int x) {
data = x;
lchild = rchild = NULL;
}
};
class tree {
protected:
Node* root;
void inorder(const Node* root)const;
public:
tree () {
root = NULL;
}
bool insert(int item);
void inorder() const {inorder(root);};
Node* getroot() {
return root;
}
};
bool tree :: insert(int item) {
if (root == NULL) {
Node *temp = new Node(item);
root = temp;
return (bool) root;
}
if (item < root -> data) {
insert(item);
}
if (item > root -> data) {
insert(item);
}
else if (item == root -> data) {
cout<<"Duplicate";
exit (0);
}
return (bool) root;
}
void tree :: inorder(const Node *root)const {
if (root != NULL) {
inorder(root -> lchild);
cout<<root -> data;
inorder(root -> rchild);
}
}
int main()
{
tree obj1;
obj1.insert(3);
//obj1.insert(4);
obj1.insert(1);
//obj1.insert(5);
obj1.inorder();
}
/* Program to implement Binary Search Tree in c++ using classes and objects */
#include<iostream>
#include<stdlib.h>
#include<cstdlib>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
class BinaryTree {
private:
struct Node* root;
public:
BinaryTree() {
root = NULL;
}
Node* createNode(int);
Node* insertNode(Node*, int);
Node* deleteNode(Node*, int);
void inOrder(Node*);
void preOrder(Node*);
void postOrder(Node*);
Node* findMinimum(Node*);
/* accessor function helps to
get the root node in main function
because root is private data member direct access is not possible */
Node* getRoot() {
return root;
}
/* mutator method helps to update root ptr after insertion
root is not directly updatable in the main because its private data member */
void setRoot(Node* ptr) {
root = ptr;
}
};
/* Helper function to create a new node in each function call of insertNode */
Node* BinaryTree :: createNode(int n) {
Node* newNode = new struct Node();
newNode->data = n;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
/* Helps to get inorder predessor to delete the node from tree */
Node* BinaryTree :: findMinimum(Node* rootPtr) {
while(rootPtr->left != NULL) {
rootPtr = rootPtr->left;
}
return rootPtr;
}
/* insertion of the Node */
Node* BinaryTree :: insertNode(Node* rootPtr, int n) {
if(rootPtr == NULL) {
return createNode(n);
}
if(n < rootPtr->data) {
rootPtr->left = insertNode(rootPtr->left, n);
}
if(n > rootPtr->data) {
rootPtr->right = insertNode(rootPtr->right, n);
}
return rootPtr;
}
/* function to delete the Node */
Node* BinaryTree :: deleteNode(Node* rootPtr, int n) {
if(rootPtr == NULL) {
cout<<"Node to be deleted is not present.!"<<endl;
return rootPtr;
}
else if(n < rootPtr->data) {
rootPtr->left = deleteNode(rootPtr->left, n);
} else if(n > rootPtr->data) {
rootPtr->right = deleteNode(rootPtr->right, n);
} else {
if(rootPtr->left == NULL && rootPtr->right == NULL) {
delete rootPtr;
rootPtr = NULL;
}
else if(root->left == NULL) {
struct Node* temp = rootPtr;
rootPtr = rootPtr->right;
delete temp;
}
else if(rootPtr->right == NULL) {
struct Node* temp = rootPtr;
rootPtr = rootPtr->left;
delete temp;
} else {
Node* temp = findMinimum(rootPtr->right);
rootPtr->data = temp->data;
rootPtr->left = deleteNode(rootPtr->right, temp->data);
}
}
return rootPtr;
}
/* all traversal technique */
void BinaryTree :: inOrder(Node* root) {
if(root == NULL) {
return;
}
inOrder(root->left);
cout<<root->data<<"\t";
inOrder(root->right);
}
void BinaryTree :: preOrder(Node* root) {
if(root == NULL) return;
cout<<root->data<<"\t";
preOrder(root->left);
preOrder(root->right);
}
void BinaryTree :: postOrder(Node* root) {
if(root == NULL) return;
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<"\t";
}
int main() {
BinaryTree l1;
int ch, ele, res;
Node* ptr;
do {
cout<<"1 - Insert Node\n";
cout<<"2 - IN-ORDER Traversal\n";
cout<<"3 - PRE-ORDER Traversal\n";
cout<<"4 - POST-ORDER Traversal\n";
cout<<"Enter choice\n";
cin>>ch;
switch(ch) {
case 1:
cout<<"Entre element to insert to the List\n";
cin>>ele;
/* calling insertNode function by passing root ptr to the function,
root ptr can be obtained by accessor function getRoot() */
ptr = l1.insertNode(l1.getRoot(), ele);
/* updating the root ptr*/
l1.setRoot(ptr);
break;
case 2:
cout<<"---IN-ORDER TRAVERSAL---"<<endl;
l1.inOrder(l1.getRoot());
cout<<endl;
break;
case 3:
cout<<"---PRE-ORDER TRAVERSAL---"<<endl;
l1.preOrder(l1.getRoot());
cout<<endl;
break;
case 4:
cout<<"---POST-ORDER TRAVERSAL---"<<endl;
l1.postOrder(l1.getRoot());
cout<<endl;
break;
case 5:
cout<<"Enter node to be deleted."<<endl;
cin>>ele;
ptr = l1.deleteNode(l1.getRoot(), ele);
l1.setRoot(ptr);
default: cout<<"Invalid choice"<<endl;
}
} while(ch >=1 && ch <= 5);
return 0;
}
The reason why root gets NULL again and again is that it actually never changes its value to something else than NULL.
Maybe you have introduced this behaviour in your code in the course of fixing some other issues; yet you assign root=NULL in the constructor; afterwards, you assign only obj.root1 = ..., while you return root in getroot() { return root; }. Further, you pass Node *root as parameter in you insert function; Note that this local variable named root hides data member root, such that root->... in these functions will always address the local variable and not the data member.
Before diving around in code that's interface needs a redesign, I'd suggest to adapt the design and then adapt the code; I'm pretty sure the errors will simply go away. I'd suggest to adapt the interface of class tree as follows and write the code around it.
Member function inorder() should be const to indicate that it does not alter the object's state. Note that const-member functions can - in contrast to other non-static member functions - be called on const-objects.
class Node {
friend class tree;
private:
Node *lchild,*rchild;
int data;
public:
Node (int x) {
data = x;
lchild = rchild = NULL;
}
};
class tree {
public:
tree () { root = NULL; }
bool insert(int item) { return insert(item,root); };
void inorder() const { inorder(root);};
protected:
Node* root;
void inorder(const Node* curr) const;
bool insert(int item, Node* curr);
};
bool tree :: insert(int item, Node *currNode) {
if (root == NULL) {
root = new Node(item);
return true;
}
else if (item < currNode->data) {
if (currNode->lchild == NULL) {
currNode->lchild = new Node(item);
return true;
}
else {
return insert(item, currNode->lchild);
}
}
else if (item > currNode->data) {
if (currNode->rchild == NULL) {
currNode->rchild = new Node(item);
return true;
}
else {
return insert(item, currNode->rchild);
}
}
else // item == currNode->data
return false; // duplicate; do not insert
}
The biggest problem with your code are the following lines:
if (item < root -> data) {
insert(item);
}
if (item > root -> data) {
insert(item);
}
Basically you are saying that if the item is larger or smaller than the root data you will call the function again with the same item, you never changed the item and you will basically do this an infinity amount of times.....

Binary Tree Insert Algorithm

I recently finished implementing a Binary search tree for a project I was working on. It went well and I learned a lot. However, now I need to implement a regular Binary Tree... which for some reason has me stumped.
I'm looking for a way to do my InsertNode function..
normally in a BST you just check if data < root then insert left and vice versa. However, In a normal Binary tree, it is just filled from left to right, one level at a time..
could anyone help me implement a function that just adds a new Node to the Binary tree from left to right in no specific order?
Here's my Insert for a BST:
void Insert(Node *& root, int data)
{
if(root == nullptr)
{
Node * NN = new Node;
root = NN;
}
else
{
if(data < root->data)
{
Insert(root->left, data);
}
else
{
Insert(root->right, data);
}
}
}
I am aware of the fact that this is a question posted some time ago, but I still wanted to share my thoughts on it.
What I would do (since this indeed is not very well documented) is use a Breadth-First-Search (using a queue) and insert the child into the first null I encounter. This will ensure that your tree will fill up the levels first before it goes to another level. With the right number of nodes, it will always be complete.
I haven't worked that much with c++, so to be sure it was correct I did it in Java, but you get the idea:
public void insert(Node node) {
if(root == null) {
root = node;
return;
}
/* insert using Breadth-first-search (queue to the rescue!) */
Queue<Node> queue = new LinkedList<Node>();
queue.offer(root);
while(true) {
Node n = queue.remove();
if(!n.visited) System.out.println(n.data);
n.visited = true;
if(n.left == null) {
n.left = node;
break;
} else {
queue.offer(n.left);
}
if(n.right == null) {
n.right = node;
break;
} else {
queue.offer(n.right);
}
}
}
Javascript implementation (copy-paste ready for your web console):
ES6 implementation (newer javscript syntax with class keyword)
class BinaryTree {
constructor(value){
this.root = value;
this.left = null;
this.right = null;
}
insert(value){
var queue = [];
queue.push(this); //push the root
while(true){
var node = queue.pop();
if(node.left === null){
node.left = new BinaryTree(value);
return;
} else {
queue.unshift(node.left)
}
if(node.right === null){
node.right = new BinaryTree(value);
return;
} else {
queue.unshift(node.right)
}
}
}
}
var myBinaryTree = new BinaryTree(5);
myBinaryTree.insert(4);
myBinaryTree.insert(3);
myBinaryTree.insert(2);
myBinaryTree.insert(1);
5
/ \
4 3
/ \ (next insertions here)
2 1
Pseudoclassical pattern implementation
var BinaryTree = function(value){
this.root = value;
this.left = null;
this.right = null;
}
BinaryTree.prototype.insert = function(value){
//same logic as before
}
With a few modifications to your code, I hope this should help :
Node * Insert(Node * root, int data)
{
if(root == nullptr)
{
Node * NN = new Node();
root = NN;
root->data = data;
root->left = root ->right = NULL;
}
else
{
if(data < root->data)
{
root->left = Insert(root->left, data);
}
else
{
root->right = Insert(root->right, data);
}
}
return root;
}
Hence , this function returns the root node of the updated BST.
I took bknopper code, modified a little bit and translated to C++. As he stated, surprisingly, this is not well documented.
Here is the node structure and the insert function:
struct nodo
{
nodo(): izd(NULL), der(NULL) {};
int val;
struct nodo* izd;
struct nodo* der;
};
void inserta(struct nodo** raiz, int num)
{
if( !(*raiz) )
{
*raiz = new struct nodo;
(*raiz)->val = num;
}
else
{
std::deque<struct nodo*> cola;
cola.push_back( *raiz );
while(true)
{
struct nodo *n = cola.front();
cola.pop_front();
if( !n->izd ) {
n->izd = new struct nodo;
n->izd->val = num;
break;
} else {
cola.push_back(n->izd);
}
if( !n->der ) {
n->der = new struct nodo;
n->der->val = num;
break;
} else {
cola.push_back(n->der);
}
}
}
}
You call it this way:
inserta(&root, val);
Being root a pointer to node struct and val the integer value you want to insert.
Hope it helps someone.
You should try using a recursive approach such as x = new (x), if you know what that means. This way, you don't really have to worry about the root node. I am going to write some pseudocode for you:
//public function
add(data){
root = add(data, root)
}
//private helper function
Node add(data, currentNode){
if(currentNode = 0)
return new Node(data)
if(data less than currentNode's data)
currentNode.left = add(data, currentNode.left)
if(data more than currentNode's data)
currentNode.right = add(data, currentNode.right)
return currentNode
}
I made a tutorial regarding the implementation of a BST in C++, here