arithmetic expression tree using c language

binary-tree c expression-trees

Question

I need to figure out how to create an arithmetic expression tree.

I can create simple binary tree using just set of numbers. There is a code example below:

This is simple node that for my tree.

typedef struct _node {
    int key;
    struct _node *left, *right;
} node;

This is how I add new node to my binary tree:

node* add_tree(node *root, int val) {    
    if(NULL == root) {
        root = crnode(val);
    }    
    if (val < root->key) {
        if (NULL == root->left) {
            root->left = crnode(val);
        }
        else {
            add_tree(root->left, val);
        }
    }

    if (val > root->key) {
        if (NULL == root->right) {
            root->right = crnode(val);
        }
        else {
            add_tree(root->right, val);
        }
    }    
    return root;
}

This is main function and steps how I add new number to tree:

int main(int argc, const char * argv[])
    {    
        node *tree = add_tree(NULL, 5);
        tree = add_tree(tree, 6);
        tree = add_tree(tree, 7);
        tree = add_tree(tree, 3);
        return 0;
    }

My question is: how to transform this code that I can using not just a number but and operator (e.g + - / *).

For example I need to transform an expression 5 * (10 - 5) + 6 * 4 to tree. How can I make it?

Accepted Answer

A node in your expression is one of two things: an operator or a value. So you need to delineate. There are several ways to do this, but since this is homework I'm inclined to be a little cagey and let you work something out using the programming concepts you have learned thus far.

So I decided to help you by showing what your tree might look like if you had your nodes working:

      +
     / \
    /   \
   /     \
  *       *
 / \     / \
5   -   6   4
   / \
  10  5

You might want to drop the notion of 'building a tree', and instead think of it as 'constructing an expression'. It could be what's holding you back. You might end up with some functions that are used like this:

node *expr = subtract(value(10), value(5));

That builds a part of the tree. See what's going on? =)



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why