DelilahDemented 0 Newbie Poster

I'm trying to build a tree from a file and it keeps blowing up on me. It doesn't even give an error but it shuts down when I try to run it. I'm not sure what is wrong. I think I have something wrong with my root but I'm really unsure. Eventually, I have to sum the root-to-leaf paths, but I'm not to this point yet. I'm trying to figure this out, but I'm really not having much luck. I am willing to learn so any help, tips, comments, or advice is greatly appreciated!

inputfile
5 8 7 4 7 3 9 2 8 _ 3 8 5 4 8 _ _ 6 _ _ 5 4 _ _ 7 _ 4 1 _
"_" indicates a blank value



#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstdlib>

using namespace std;

ofstream outFile;
ifstream inFile;

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);
};

node* insert(node* node, int data)
{
    //Empty Tree
    if(node == NULL)
    {
        return(NewNode(data));
    }
    else
    {
        //Find next spot in the tree
        if(data <= node->data)
        {
            node->left = insert(node->left, data);
        }
        else
        {
            node->right = insert(node->right, data);
        }

        return(node);
    }
};

void printTree(struct node* node);
int hasPathSum(node* node, int sum);

int main()
{
    //Open inFile
    inFile.open("SumOfPath.txt");

    //Check to see if file opened
    while(!inFile)
    {
        cout << "Error opening the inFile." << endl;
        return 1;
    }

    //Open outFile
    outFile.open("Results.txt");

    //Check to see if file opened
    while(!outFile)
    {
        cout << "Error opening the outFile." << endl;
        return 1;
    }

    //Declare variables
    node* root;
    int c = inFile.get();

    while (!inFile.eof())
    {
        node* insert(node* root, int c);
        //outFile.put(c);
        c = inFile.get();
    }

    printTree(root);

    //Close files
    inFile.close();
    outFile.close();

    return 0;
}

void printTree(struct node* node)
{
    if(node == NULL)
    {
        return;
    }

    printTree(node->left);
    printf("%d ", node->data);
    printTree(node->right);
}

int hasPathSum(node* node, int sum)
{
    //return true if no tree and sum == 0
    if(node == NULL)
    {
        return(sum == 0);
    }
    else
    {
        int subSum = sum - node->data;
        return(hasPathSum(node->left, subSum)) || (hasPathSum(node->right, subSum));
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.