Reding in a file to a binary tree

I am trying to read in a list of numbers from an external file to a binary tree. And I just can't seem to get the file to read in if I manually insert it works if I try to read in the file nothing happens. And I know a binary tree probably isn't the best data structure to use for this but I wanted to try.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

//root node
//pointer to left and right child node
struct node
{
	int key;
	struct node *left;
	struct node *right;
};

//utility function to make node
struct node *newNode(int item)
{
	struct node *temp = (struct node *)malloc(sizeof(struct node));
	
	temp->key = item;
	temp->left = temp->right = NULL;
	return temp;
};

//utility to perform in order traversal of BST
void inorder(struct node *root)
{
	if (root != NULL)
	{
		inorder(root->left);
		cout << root->key << endl;
		inorder(root->right);
	}
}

//insertion utility
struct node* insert(struct node* node, int key)
{
	//if tree is empty return a new node
	if (node == NULL) return newNode(key);

	//otherwise recur down tree
	if (key < node->key)
		node->left = insert(node->left, key);
	else if (key > node->key)
		node->right = insert(node->right, key);

	//return unchanged node pointer
	return node;
}

int main()
{
	struct node *root = NULL;
	int counterNumber = 0;

	ifstream infile;
	infile.open("Text.txt");
	
	while (infile.is_open())
	{
		root = insert(root, counterNumber);
	}

	infile.close();

	//print inorder traversal
	inorder(root);

	system("pause");
	return 0;
}
You never read anything from the file, so it sits in an infinite loop calling insert().
1
2
3
4
	while (infile.is_open())
	{
		root = insert(root, counterNumber);
	}
read out loud.

nothing in the body of the loop would modify its condition
so never executes or run forever
Topic archived. No new replies allowed.