Home > Enterprise >  Having trouble with addresses/pointers in my tree with structs as nodes. I don't seem to be ins
Having trouble with addresses/pointers in my tree with structs as nodes. I don't seem to be ins

Time:09-21

I'm having trouble with inserting into my expression tree. My Expression tree is made up of Expression nodes. These Expression nodes contain either an enum, Operation, or a string. Each Expression node also having a leftArgument/rightArgument pointers to Expressions (leftNode address and rightNode address).

Of course, my addNode function is clearly not implemented fully, however I expect this code to insert (5) Expression nodes, and each being inserted to the left, creating a very left-heavy tree.

However, it seems to only be rewriting the Expression node in the second level of my tree when executing. There is something wrong with my pointers/addresses within my main() or addNode() function and after hours, I can't seem to figure it out.

Any hints or observations would be greatly appreciated! Thank you so much.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "expressions.h"

typedef enum Operation {
    FIRST = 1,
    REST = 2,
    CONS = 3,
} Operation;

union Data {
    Operation operation;
    char *string;
};

struct Expression {
    Data data;
    Expression *leftArgument;
    Expression *rightArgument;
};

char* eval(Expression e) {
    return "0";
}

Expression *addNode(Expression *e, Expression *tree) {
    if (tree == NULL) {
        tree = malloc(sizeof(Expression));
        tree->data = e->data;
        tree->leftArgument = NULL;
        tree->rightArgument = NULL;

        printf("added new node\n");
    } else if (tree->data.operation == FIRST || tree->data.operation == REST) {
        printf("%d\n", tree->data.operation);
        addNode(e, tree->leftArgument);
    } 

    return tree;
}

int main() {
    Expression *tree = NULL;

    printf("----------[INSERT]-----------\n");
    Expression e1;
    e1.data.operation = FIRST;
    tree = addNode(&e1, tree);
    printf("-----------------------------\n\n");

    printf("----------[INSERT]-----------\n");
    Expression e2;
    e2.data.operation = REST;
    tree = addNode(&e2, tree);
    printf("-----------------------------\n\n");

    printf("----------[INSERT]-----------\n");
    Expression e3;
    e3.data.operation = FIRST;
    tree = addNode(&e3, tree);
    printf("-----------------------------\n\n");

    printf("----------[INSERT]-----------\n");
    Expression e4;
    e4.data.operation = REST;
    tree = addNode(&e4, tree);
    printf("-----------------------------\n\n");
}

CodePudding user response:

In the recursive function call

addNode(e, tree->leftArgument);

you are discarding the return value which contains the new root of the tree.

You probably intended to write:

tree->leftArgument = addNode(e, tree->leftArgument);
  • Related