BFS Binary Search tree

// BST.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

class BST
{
struct Node
{
int data;
struct Node *leftchild;
struct Node *rightchild;
}*root;
public:
BST()
{
root = NULL;
}
void insertion(int data); // Insert operation
Node* serach(int data);
};
void BST::insertion(int data)
{
Node *tempNode = (Node*)malloc(sizeof(struct Node));
struct Node *current;
struct Node *parent;

tempNode->data = data;
tempNode->leftchild = NULL;
tempNode->rightchild = NULL;

if(root == NULL)
{
root = tempNode;
return;
}
else
{
current = root;
parent = NULL;
}
while(1)
{
parent = current;
if(tempNode->data > parent->data)
{
current = current->rightchild;
if(current == NULL)
{
parent->rightchild = tempNode;
return;
}
}
if(tempNode->data < parent->data)
{
current = current->leftchild;
if(current == NULL )
{
parent->leftchild = tempNode;
return;
}
}
}

}
BST::Node* BST::serach(int data)
{
Node* current = root;

while(current->data != data)
{
if(current != NULL)
printf("%d",current->data);
if(current->data < data)
current = current->rightchild;
else
current = current->leftchild;
if(current == NULL)
return NULL;
}
return current;
}

int _tmain(int argc, _TCHAR* argv[])
{
BST obj;
obj.insertion(20);
obj.insertion(10);
obj.insertion(56);
obj.insertion(41);
obj.insertion(30);
obj.insertion(5);
BST obj2;
obj.serach(41);
return 0;
}

Comments

Popular posts from this blog

Smart Pointers in C++ and How to Use Them

Operator Overloading in C++

How would you read in a string of unknown length without risking buffer overflow