insertion in binary search tree (C++) - c++

I'm new to data structure.
I'm making a C++ program for insertion of an element in binary search tree .
The program compiles without any error but when I'm running the program , after giving the first input n , the program stops working.
Kindly help me in making this program work properly.
My code follows up as:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node *root=NULL ,*par=NULL ,*pos=NULL,*save=NULL , *ptr=NULL ;
struct node* newNode(int data)
{
struct node* newnode= (struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->right=NULL;
newnode->left=NULL;
return newnode;
}
void findpos(int data)
{
if(root==NULL)
{
par=NULL,pos=NULL;
return;
}
if(root->data==data)
{
par=NULL , pos=root;
return;
}
if(data<root->data)
{
save=root; ptr=root->left;
}
else{
save=root; ptr=root->right;
}
while(ptr!=NULL)
{
if(ptr->data==data)
{
par=save; pos=ptr;
return;
}
if(data<ptr->data)
{
save=ptr;
ptr=ptr->left;
}
else{
save=ptr;
ptr=ptr->right;
}
}
pos=NULL; par=save;
return;
}
void insert(int data)
{
findpos(data);
if(pos!=NULL)
{
return;
}
pos=newNode(data);
if(data<par->data)
par->left=pos;
else
par->right=pos;
return;
}
int main()
{
struct node *root= newNode(4);
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
int n;
cin>>n;
insert(n);
cout<<pos->data; //just trying to see if it works
return 0;
}

The root pointer declared in the main() override the global root pointer. Then at the first findpos(), the root (global) is still NULL.
So, simply replace that code:
int main()
{
struct node *root= newNode(4);
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
int n;
cin>>n;
insert(n);
cout<<pos->data; //just trying to see if it works
return 0;
}
By this one:
int main()
{
root= newNode(4);
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
int n;
cin>>n;
insert(n);
cout<<pos->data; //just trying to see if it works
return 0;
}

Changed the main method so that it modifies root in global namespace; before you were declaring a new node called root localy within main.
int main() {
// struct node *root = newNode(4); // you made this root a member of main.
// not a global member anymore.
root = newNode(4); // use this
// Populate some nodes
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
/* tree so far:
* 4
* / \
* 3 6
* /
* 2
*/
int n;
cin >> n;
cout << "user input " << n << "\n";
insert(n);
cout << pos->data; //just trying to see if it works
return 0;
}

Related

Segmentation fault in passing pointer to a linked list

Hello fellow programmers, the below code gives segmentation fault. This code aims to insert an element at the end of a linked list. I tried using print statements to debug it. I think the error is in passing the linked list pointer to insert() function. Please tell me how can I correct it. Thanks in advance.
Below is the code:
#include <iostream>
using namespace std;
class node {
public:
int data;
node *next;
node(int data) {
this->data = data;
this->next = NULL;
}
};
class linked_list {
public:
node *head;
linked_list() {
this->head = NULL;
}
};
void insert(node **head, int data);
void print(linked_list *L);
int main() {
int N;
linked_list *A = new linked_list();
cout << "N: ";
cin >> N;
for(int i=0; i<=N-1; i++) {
int t;
cin >> t;
insert(&(A->head), t);
}
print(A);
return 0;
}
void insert(node **head, int data) {
node *temp = new node(data);
if(*head == NULL) {
*head = temp;
return;
} else {
node *t = *head;
while(t->next != NULL) {
t=t->next;
}
t->next = temp;
return;
}
}
void print(linked_list *L) {
node * t = L->head;
while(t!=NULL) {
cout << t->data << " ";
t = t->next;
}
return;
}
main.cpp:42:14: error: using the result of an assignment as a
condition without parentheses [-Werror,-Wparentheses]
if(*head = NULL) {
~~~~~~^~~~~~
main.cpp:42:14: note: place parentheses around the assignment to
silence this warning
if(*head = NULL) {
^
( )
main.cpp:42:14: note: use '==' to turn this assignment into an
equality comparison
if(*head = NULL) {
^
==
1 error generated.
You're using assignment where you intended to do a comparison.

what is the problem in creat_list2 function?

I want to know what is the problem in creat_list2 function..
I have a problem in this code and as i knew it's in the creat_list2 cause the program run Successfully
when i stop this function it ask the user to enter a numbers that will be stored in the list 1 then print them but the problem as i saw is in the second fuction that creat the second list...,I have to submit my assignment tomorrow so I wish if any body can help me to solve this problem.
#include<iostream>
using namespace std;
struct node{
int x;
node *next;
};
struct snode{
int y;
snode *next;
};
creat_list1(node *&head, node *&tail)
{
int num;
cout<<"enter number\n";
cin>>num;
while(num!=0)
{
node *np=new node;
np->x=num;
if(head==nullptr)
head=np;
else
tail->next=np;
tail=np;
tail->next=nullptr;
cout<<"enter number again\n";
cin>>num;
}
}
creat_list2(node *&head, snode *shead, snode *stail)
{
int sum=0;
while(head!=nullptr)
{
for(int i=0;i<head->x;i++)
sum+=i;
snode *np= new snode;
np->y=sum;
if(head==0)
shead=np;
else
stail->next=np;
stail=np;
stail->next=nullptr;
}
head=head->next;
}
void print_list1 (node *head)
{
while(head!=nullptr)
{
cout<<head->x<<"\t";
head=head->next;
}
}
void print_list2(snode *shead)
{
while(shead!=nullptr)
{
cout<<shead->y<<"\t";
shead=shead->next;
}
}
main()
{
node *head=nullptr, *tail=nullptr;
snode *shead=nullptr, *stail=nullptr;
creat_list1(head,tail);
creat_list2(head,shead,stail);`enter code here`
print_list1(head);
print_list2(shead);
}
There are couple of issues with yours code,
creat_list2(node *&head, snode *shead, snode *stail) if u updated
head like head=head->next; it will reflect at the main.
shead and stail are just a local pointer and any update to just a pointer like stail=np;will not have any changes at the `main
There seems to be typo if(head==0) shead=np; instead it should be
if(shead==0) shead=np; which is causing null pointer exception.
I tried to fix the error at creat_list2 but functionality is still ambiguous to me,
void creat_list2(const node *head, node *&shead, node *&stail) //updated in argument
{
int sum = 0;
while (head != nullptr)
{
//for (int i = 0; i < head->x; i++)
// sum += i;
node *np = new node;
np->x = sum;
if (shead == 0) //error : head instead shead
shead = np;
else
stail->next = np;
stail = np;
stail->next = nullptr;
head = head->next;
}
}

Inserting data in a singly link list by specifying the nth node position

So the logic goes like this:
Suppose the link list consists of (6,7,8) as data and I pass insert(1,5),so the list will be as (5,6,7,8).
Similarly on insert(3,2) link list is (6,7,2,8).
I tried compiling the below code but it gives me an error stating-
Undefined reference to main by '-start'
I tried debugging,even searching for answers but found no help.Kindly suggest a solution.Any further suggestions and bug fixes shall be welcomed.
(I have used codepad for compiling)
#include<iostream>
using namespace std;
class Link_no
{
struct node
{
int data;
node *next;
};
void insert(int n,int d,node *head)
{
node *temp=new node();
temp->data=d;
temp->next=NULL;
node *temp1;
if(n==1)
{
temp->next=head;
head=temp;
return;
}
else
temp1=head;
{
for(int i=0;i<n-1;i++)
{
temp1=temp1->next;
}
temp->next=temp1;
temp1=temp;
}
}
void print(node *start)
{
node *temp=start;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
int main()
{
node *head=NULL;
Link_no o1;
o1.insert(1,5,head);
o1.insert(2,7,head);
o1.insert(1,9,head);
o1.print(head);
return 0;
}
}
C++ isnt java, the main does not belong inside a class. The compiler complains because there is no int main() in your code only a int Link_no::main() but that is not the entry point of the program.
Take out int main() from class Link_no. Take out struct node from class Link_no. It should compile.
The following compiles
#include<iostream>
using namespace std;
class Link_no
{
private:
struct node
{
int data;
node *next;
};
node *head;
public:
Link_no(){
head = nullptr;
}
void insert(int n,int d)
{
node *temp=new node();
temp->data=d;
temp->next=NULL;
node *temp1;
if(n==1)
{
temp->next=head;
head=temp;
return;
}
else
temp1=head;
{
for(int i=0;i<n-1;i++)
{
temp1=temp1->next;
}
temp->next=temp1;
temp1=temp;
}
}
void print()
{
node *temp=head;
while(temp!=NULL)
{
cout << "data is " << temp->data<<endl;
temp=temp->next;
}
}
};
int main()
{
Link_no o1;
o1.insert(1,5);
o1.insert(2,7);
o1.insert(1,9);
o1.print();
return 0;
}
It does not completely do what you want yet only prints out 5 and 9 as data so you need to debug some more.
Edit:
I suggest you take a paper and pen and manually try to do what you're doing in your else since there is something going wrong there.
If you can't find it out on your own the following works for me, I haven't tried testing for extreme cases yet.
#include<iostream>
using namespace std;
class Link_no
{
private:
struct node
{
int data;
node *next;
};
node *head;
public:
Link_no(){
head = nullptr;
}
void insert(int n,int d)
{
node *temp=new node();
temp->data=d;
temp->next=NULL;
node *temp1;
if(n==1)
{
temp->next=head;
head=temp;
return;
}
else
{
cout << "foo" << endl;
temp1=head;
for(int i=1;i<n-1;i++)
{
temp1=temp1->next;
}
node *temp2 = temp1->next;
temp1->next = temp;
temp->next=temp2;
}
}
void print()
{
node *temp=head;
cout << "link" << endl;
while(temp!=NULL)
{
cout << "data is " << temp->data<<endl;
temp=temp->next;
}
}
};
int main()
{
Link_no o1;
o1.insert(1,5);
o1.print();
o1.insert(2,7);
o1.print();
o1.insert(1,9);
o1.insert(2,6);
o1.print();
return 0;
}

Why isn't my printLevel function working?

I have written this code to do level order traversal of Binary Search tree. Error is only in printLevel function because all other functions are working fine.
#include <queue>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data){
struct node* node = new (struct node);
node->data=data;
node->left=NULL;
node->right=NULL;
return (node);
};
struct node* insert (struct node* node, int data){
if (node==NULL){
return (newNode(data));
}
else {
if (data<=node->data) node-> left=insert(node->left,data);
else node->right=insert(node->right,data);
return (node);
}
}
void printLevel(struct node* node){
queue<struct node*> q;
while(node!=NULL){
cout << node->data << " ";
q.push(node->left);
q.push(node->right);
node=q.front();
}
}
int main(){
int n;
cin >>n;
int m;
cin >>m;
struct node* root=newNode(m);
for (int i=0;i<n-1;i++){
cin>>m;
insert(root,m);
}
printLevel(root);
// printPostOrder(root);
// cout <<maxDepth(root);
// debug(maxDepth(root), minValue(root), printTree(root));
//struct node* root=build123();
}
Here is the algorithm: (http://www.geeksforgeeks.org/level-order-tree-traversal/)
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /start from root/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
I am taking input 3,1,4,2,7,6,5 for 7 nodes. It gets stuck in infinite loop. I have also implemented following two functions based on another method and it is working fine:
void levelOrder(struct node* node, int level ){
if (node==NULL){
return;
}
if (level==1){
cout << node->data;
}
else if (level>1){
levelOrder(node->left,level-1);
levelOrder(node->right,level-1);
}
}
void printLevelOrder(struct node* root){
for (int i=1;i<=maxDepth(root);i++){
levelOrder(root,i);
}
}
It is O(n^2) but above one is O(n). What's wrong with my code? Thanks.
I suspect that your loop termination is wrong.
Instead of node != NULL, you should check to see if !q.empty().
Also, the call q.front does not remove the element from the queue; to do that, you need pop (after calling front).
This code works for me:
void printLevel(struct node* node){
std::queue<struct node*> q;
q.push(node);
while(!q.empty()) {
node=q.front();
q.pop();
if ( node != NULL ) {
std::cout << node->data << " ";
q.push(node->left);
q.push(node->right);
}
}
}

Weird segmentation fault that disappears on using cout

I'm trying out a basic program that will randomly initialize a linked list and print the value at a user-specified index (getnth). However, I'm running into a weird segmentation fault that appears when I comment out a specific cout line, and disappears when I uncomment it.
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int x;
node *next;
};
void ins(struct node*& headRef, int n)
{
node *newNode = new node;
if (!newNode)
return;
newNode->x = n;
if (!headRef)
newNode->next = NULL;
else
newNode->next = headRef;
headRef = newNode;
cout<<"\n"<<n<<" inserted at "<<headRef<<"\n\n";
}
void disp(struct node* head)
{
node *temp = head;
if (!temp)
{
cout<<"\n\nLL empty\n";
return;
}
while (temp)
{
cout<<temp->x<<" ";
temp = temp->next;
}
cout<<"\n\n";
}
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
if (i == n)
{
cout<<"\n"<<temp->x<<"\n\n";
return;
}
}
cout<<"\nIndex too high\n";
}
int main()
{
node *head;
int i;
srand(time(NULL));
for (i=0; i<10; i++)
{
ins(head, rand()%10+1);
cout<<"Main head is "<<head<<"\n"; // segfault appears if this line is commented out, disappears if it's not
}
cout<<"\nInitial LL\n\n";
disp(head);
cout<<"\nEnter index ";
cin>>i;
getnth(head, i);
return 0;
}
In main initialize
node *head=NULL;
and your getnth is wrong , fix it.
May be something like this :-
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
if (++i == n)
{
cout<<"\n"<<temp->x<<"\n\n";
return;
}
temp=temp->next;
}
cout<<"\nIndex too high\n";
}
By default, the pointer "head" in "main( )" is initialized with garbage, because it's automatic variable allocated on program stack.
So, when you pass the pointer "head" to the function "disp( )", this pointer is dereferenced and it causes segmentation fault.
You have to initialize the pointer "head" with 0 explicitly, and this will fix the problem.