Alright, so I've spent countless hours on this code and I need a fresh pair of eyes to give it a glance...
This is my third assignment for my datastructures class, where I am to write code that turns a fully parenthesized expression (such as "((3+2)/(3-8))") into aan "arithemtic expression tree", where the internal nodes are operators and the external nodes are operands.
The following function that I have written contains a logic error somewhere I suppose, because it simply crashes when I call it. My approach uses recursion, and the function contains parameters to pass the expression (in string form), and start and end indicators (in int form, to tell the function what section of the expression it is currently dealing with).
Most of the logic in the algorithm is based around the brackets in the expression; using them to figure out where the next operator is, boundaries of the chunk of the expression, etc...
Anyway, here she is... Any help would be greatly appreciated!
typedef struct _Tree{
char* value;
struct _Tree* parent;
struct _Tree* leftChild;
struct _Tree* rightChild;
}Tree;
Tree* newNode (char* exprssn, int strt, int end){
int i, oBrkts, cBrkts; // Counter Variables
Tree* node;
node->value = malloc (sizeof (char)*6);
int operator = 0;
char* subExprssn;
for (i = strt; i < end; i++){
if (exprssn [strt] == '('){
if (exprssn [i] == '(') oBrkts++;
if (exprssn [i] == ')') cBrkts++;
if (oBrkts == cBrkts && cBrkts > 0){
strcpy(node->value, exprssn [i+1]+"");
node->leftChild = newNode (exprssn, strt+1, i - 1);
node->rightChild = newNode (exprssn, i+1, end - 1);
}
}else{
if (exprssn [i] == '*' || exprssn [i] == '/' || exprssn [i] == '+' || exprssn [i] == '-'){
strcpy (node->value, exprssn [i]+"");
sprintf (subExprssn, "%.*s", (i - 1) - strt, &exprssn [strt]);
node->leftChild->value = malloc (sizeof (char)*6);
strcpy (node->leftChild->value, subExprssn);
sprintf (subExprssn, "%.*s", (i - 1) - strt, &exprssn [strt]);
node->rightChild->value = malloc (sizeof (char)*6);
strcpy (node->rightChild->value, subExprssn);
}else if ((i + 1) == end){
sprintf (subExprssn, "%.*s", end - strt, &exprssn [strt]);
strcpy (node->value, subExprssn);
}
}
}
return node;
}
int main () {
//Allocate memory for user input//
char* input = malloc (sizeof (char)*41);
//Get input from user//
printf ("Please enter a fully parenthesized algebraic expression with\nno more then two terms per bracket, and no spaces: ");
scanf ("%s", input);
//Call the recursive tree creating function "newNode"//
Tree* root = newNode (input, 1, strlen (input) - 1);
}