Trouble with tree
Nov 9, 2012 at 9:55pm UTC
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!
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
input:
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));
}
}
Last edited on Nov 9, 2012 at 9:59pm UTC
Topic archived. No new replies allowed.