I am trying to implement DSs in C++ and this is BST insert and search functions. I tried in two different ways, please review and see if one is advantageous over other.
With pointer to pointer
#include <stdio.h>
#include <iostream>
struct BstNode{
int data;
BstNode* left;
BstNode* right;
};
BstNode* NewNode(int data)
{
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void Insert(BstNode** root,int data)
{
if(*root == NULL)
{
*root= NewNode(data);
}
else if(data <= (*root)->data)
{
(*root)->left = NewNode(data);
}
else
{
(*root)->right = NewNode(data);
}
}
bool SearchBST(BstNode* root, int data)
{
if(root == NULL)
{
return false;
}
else if(root->data == data)
{
return true;
}
else if(data <= root->data)
{
return SearchBST(root->left, data);
}
else
{
return SearchBST(root->right, data);
}
}
int main()
{
BstNode* ptr_root = NULL;
Insert(&ptr_root,15);
Insert(&ptr_root,10);
Insert(&ptr_root,16);
int num;
std::cout<<"Enter the number: \n";
std::cin>> num;
if (SearchBST(ptr_root,num))
std::cout<<"Found\n";
else
std::cout<<"Not Found\n";
return 0;
}
Without pointer to a pointer:
#include <stdio.h>
#include <iostream>
struct BstNode{
int data;
BstNode* left;
BstNode* right;
};
BstNode* NewNode(int data)
{
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
BstNode* Insert(BstNode* root,int data)
{
if(root == NULL)
{
root= NewNode(data);
}
else if(data <= root->data)
{
root->left = NewNode(data);
}
else
{
root->right = NewNode(data);
}
return root;
}
bool SearchBST(BstNode* root, int data)
{
if(root == NULL)
{
return false;
}
else if(root->data == data)
{
return true;
}
else if(data <= root->data)
{
return SearchBST(root->left, data);
}
else
{
return SearchBST(root->right, data);
}
}
int main()
{
BstNode* ptr_root = NULL;
ptr_root=Insert(ptr_root,15);
ptr_root=Insert(ptr_root,10);
ptr_root=Insert(ptr_root,16);
int num;
std::cout<<"Enter the number: \n";
std::cin>> num;
if (SearchBST(ptr_root,num))
std::cout<<"Found\n";
else
std::cout<<"Not Found\n";
return 0;
}