0

Hi Guys. I tried creating an insert into tree datastructure which is causing core dump.

Please identify the issue...

Here is the code

#include<iostream>
#include<string>
#include<stdlib.h>

using namespace std;

//Global Data

struct Tree
{
	Tree* right;
	Tree* left;
	int element;
};
typedef struct Tree* TreeData;

//Function Declaration

void insert(TreeData &data,int element);


int main()
{
	string tree_value;
	int tree_elem;
	TreeData main_tree;
	cout<<"Enter Numbers to Insert in Tree"<<endl;
	cout<<"TO END THE SEQUENCE ENTER "<<endl;
	while(1)
	{

	cin>>tree_value;
	if(!tree_value.compare("*")==0)
	{
	tree_elem=atoi(tree_value.c_str());
	cout<<"Tree element is"<<tree_elem<<endl;
	insert(main_tree,tree_elem);
	}
	else
	{
		exit(0);
	}
	}

	cout<<main_tree->element<<endl;
}

void insert(TreeData &data,int element)
{
	cout<<"Inside Insert"<<endl;
	if(data == NULL)
	{
		cout<<"Data is NULL"<<endl;
		data=(TreeData)malloc(sizeof(TreeData));
		if(data==NULL)
		{

			cout<<"Error Allocating Memory"<<endl;
			exit(0);
		}
		else
		{
			cout<<"element"<<element<<endl;
			data->element=element;
			data->right=NULL;
			data->left=NULL;
		}

	}
	else
	{
		if(element<data->element)
		{
			insert(data->right,element);
		}
		else if(element>data->element)
		{
			insert(data->left,element);
		}
	}

}

Edited by Narue: Added code tags

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by hag++
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.