Link to home
Start Free TrialLog in
Avatar of dshrenik
dshrenikFlag for United States of America

asked on

Binary Tree

I'm finding it hard do debug the attached code that constructs a binary search tree.
Please let me know what I am missing.

Thanks!
treeNode* constructBinaryTree()
{
	treeNode **root = new treeNode*;
	treeNode *current = new treeNode;
	//root = NULL;
	//current = NULL;
	int data = 0;

	while( data!= -1)
	{
		printf("\n\nEnter a value (Enter -1 to stop): ");
		scanf("%d", &data);

		treeNode *newNode = new treeNode;
		newNode->left = NULL;
		newNode->right = NULL;
		newNode->data = data;

		if(!current)
		{
			*root = newNode;
		}
		else
		{
			current = *root;
			while(current->left || current->right)
			{
				if(data<=current->data)
					current = current->left;
				else 
					current = current->right;
			}
			if(data<=current->data)
					current->left = newNode;
			else 
				current->right = newNode;
		}
	}

	return *root;
}

Open in new window

#include <iostream>
#include <conio.h>
#pragma once

typedef struct treeNode
{
	struct treeNode *left;
	struct treeNode *right;
	int data;
} treeNode;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Superdave
Superdave
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dshrenik

ASKER

Thank you!

Can you tell me why I must not initialize them to NULL, and why I must not use "new" to declare them?

It is working better now, but not for all inputs. When I enter 3, 4, 5, -1 it creates the tree without any problems.

When I enter 3, 4, 1, then I get an exception : "Access violation reading location 0x00000000."

My code now looks like this:
This code now works:

Thanks!
#include <iostream>
#include <conio.h>
#include "treeNode.h"
#pragma once

treeNode* constructBinaryTree()
{
	treeNode *root = new treeNode;
	treeNode *current = new treeNode;
	treeNode *previous = new treeNode;
	root = NULL;
	current = NULL;
	previous = NULL;
	int data;

	while(1)
	{
		printf("\n\nEnter a value (Enter -1 to stop): ");
		scanf("%d", &data);
		if(data==-1)
			break;

		treeNode *newNode = new treeNode;
		newNode->left = NULL;
		newNode->right = NULL;
		newNode->data = data;

		current = root;
		previous = root;
		
		if(!current)
		{
			root = newNode;
		}
		else
		{			
			while(current)
			{
				previous = current;

				if(data <= current->data)
					current = current->left;
				else 
					current = current->right;
			}
			if(data<=previous->data)
					previous->left = newNode;
			else 
				previous->right = newNode;
		}
	}

	return root;
}

Open in new window