'arithmetic expression tree using c language
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
