tree creation for an expression


 
Thread Tools Search this Thread
Top Forums Programming tree creation for an expression
# 1  
Old 10-08-2009
tree creation for an expression

i have written a program for creating an infix tree for the given expression.
the program is working fine if we give the expression completlely binded with operators and operands but when we ignore the brackets we need to consider the priority of the operators nad build the tree.

i am not getting the idea how to do that.

i have tried with a pen and paper but my efforts are in vain.

any suggestions on how can i change my program so that it works for both the inputs.

you can have a look at my code.



Code:
 
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "BST.h"
#define EMPTY 0
void push_exp(int item);
int pop_exp();
int is_stk_exp_empty();
void push_tree();
BST_t *pop_tree();
int is_stk_tree_empty();
BST_t * infixtree(char* infix);
struct stack_exp
{
        int data[MAX];
        int top;
};
struct stack_exp ex;
struct stack_tree
{
        BST_t *nodes[100];
  int top;
};
struct stack_tree tree;
int emptystacks()
{
        ex.top =-1;
        tree.top =-1;
}
void push_exp(int item)
{
                ++ex.top;
                ex.data[ex.top]=item;
}
int pop_exp()
{
        int ret =0;
        if(ex.top != -1)
        {
                ret= ex.data[ex.top];
                --ex.top;
        }
        return ret;
}
int is_stk_exp_empty()
{
 if(ex.top == -1)
                return 1;
        else
                return 0;
}
int isoperator(char e)
{
        if(e == '+' || e == '-' || e == '*' || e == '/' || e == '%'|| e == '^')
                return 1;
        else
                return 0;
}
BST_t *create_node(int n1)
{
        BST_t *newnode;
        newnode = (BST_t *)malloc(sizeof(newnode));
        newnode->data=n1;
        newnode->left=NULL;
        newnode->right=NULL;
        return newnode;
}
int isoper(char ch)
{
  char op;
        switch(ch)
        {
        case '+':
        case '-':
        case '/':
        case '*':
        case '^':
                op =1;
                break;
        default:
                op=0;
                break;
        }
return op;
}
 
BST_t * infixtree(char* infix)
{
        char *i,*p;
        char n1;
        BST_t *temp,*r,*l,*root,*t;
        i = &infix[0];
        while(*i)
        {
 
                while(isblank(*i) && *i != '\0')
   {
                        i++;
                }
 
                if( isdigit(*i) || isalpha(*i))
                {
                        while( isdigit(*i) || isalpha(*i))
                        {
                                push_exp(*i);
                                i++;
                        }
                }
                if(isoper(*i))
                {
                        push_exp(*i);
                }
                if( *i == '(' )
                {
                        push_exp(*i);
                }
                if( *i == ')')
                {
                while( (n1 = pop_exp()) != '(')
                {
                  if(isoperator(n1))
                   {
                     temp = create_node(n1);
      t = pop_tree();
                     if(t)
                       temp->right = t;
                   }
                  else
                  {
                    r=create_node(n1);
                    push_tree(r);
                  }
                }
                l=pop_tree();
                if(l){
                        temp->left=l;
                        root=temp;
                        push_tree(root);
                }
}
i++;
}
return root;
}
void push_tree(BST_t *t)
{
        tree.top++;
        tree.nodes[tree.top]=(BST_t *)malloc(sizeof(BST_t));
        tree.nodes[tree.top]=t;
}
 
BST_t *pop_tree()
{
        if(tree.top > -1 )
         return tree.nodes[tree.top--];
        else
         return NULL;
}
int is_stk_tree_empty()
{
        if(tree.top == -1)
                return 1;
        else
                return 0;
}
void inorder(BST_t * root)
{
        if(root != NULL )
        {
            inorder(root->left);
            printf("%c", root->data);
     inorder(root->right);
        }
}
 
int main()
{
      char in1[70],in2[70],post[50],ch;
      BST_t * root1, *root2;root1=root2=NULL;
      int i=0;
      printf(" Exp: \"( a + ( ( ( ( b * c ) ^ d ) / ( e + f ) ) * g) )\"\n");
      strcpy(in1," ( a + ( ( ( ( b * c ) ^ d ) / ( e + f ) ) * g))"); '
      emptystacks();
      root1 = infixtree(in1);
      inorder(root1);
      printf("\n");
      printf("Exp : \"a + b * c ^ d / ( e + f ) * g\" \n");
      strcpy(in2,"a + b * c ^ d / ( e + f ) * g"); 
      emptystacks();
      root2 = infixtree(in2);
      inorder(root2);
return 0;
}

# 2  
Old 10-08-2009
"The AWK Programming Language" book page 146 may offer some hint:
Code:
# calc3 - infix calculator

NF > 0 {
    f = 1
    e = expr()
    if (f <= NF) printf("error at %s\n", $f)
    else printf("\t%.8g\n", e)
}

function expr(  e) {        # term | term [+-] term
    e = term()
    while ($f == "+" || $f == "-")
        e = $(f++) == "+" ? e + term() : e - term()
    return e
}

function term(  e) {        # factor | factor [*/] factor
    e = factor()
    while ($f == "*" || $f == "/")
        e = $(f++) == "*" ? e * factor() : e / factor()
    return e
}

function factor(  e) {      # number | (expr)
    if ($f ~ /^[+-]?([0-9]+[.]?[0-9]*|[.][0-9]+)$/) {
        return $(f++)
    } else if ($f == "(") {
        f++
        e = expr()
        if ($(f++) != ")")
            printf("error: missing ) at %s\n", $f)
        return e
    } else {
        printf("error: expected number or ( at %s\n", $f)
        return 0
    }
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Unable to find files, those can be present anywhere in the directory tree,based on its creation date

Hi I am unable to find files, those are present anywhere in the same directory tree, based on the creation date. I need to find the files with their path, as I need to create them in another location and move them. I need some help with a script that may do the job. Please help (2 Replies)
Discussion started by: sam192837465
2 Replies

2. Shell Programming and Scripting

Why Relational Expression is Writing to a Expression?

Hello All, Not sure why this is happening... When the following If Statement is evaluated for some reason it is creating a file in the CWD called '0'. I've seen this happen before, just not in an If Statement... CODE: if then DIR_NAME="$1" DIR_SIZE=0 STATUS="" else... (3 Replies)
Discussion started by: mrm5102
3 Replies

3. UNIX for Advanced & Expert Users

sed: -e expression #1, char 0: no previous regular expression

Hello All, I'm trying to extract the lines between two consecutive elements of an array from a file. My array looks like: problem_arr=(PRS111 PRS213 PRS234) j=0 while } ] do k=`expr $j + 1` sed -n "/${problem_arr}/,/${problem_arr}/p" problemid.txt ---some operation goes... (11 Replies)
Discussion started by: InduInduIndu
11 Replies

4. Programming

Perl: How to read from a file, do regular expression and then replace the found regular expression

Hi all, How am I read a file, find the match regular expression and overwrite to the same files. open DESTINATION_FILE, "<tmptravl.dat" or die "tmptravl.dat"; open NEW_DESTINATION_FILE, ">new_tmptravl.dat" or die "new_tmptravl.dat"; while (<DESTINATION_FILE>) { # print... (1 Reply)
Discussion started by: jessy83
1 Replies

5. UNIX for Dummies Questions & Answers

Tree command

How can i install tree command in ubundu without root ? I have found some shell script which does the same job as tree but i would like to get all the options in tree command thanks (2 Replies)
Discussion started by: gvj
2 Replies

6. Shell Programming and Scripting

Integer expression expected: with regular expression

CA_RELEASE has a value of 6. I need to check if that this is a numeric value. if not error. source $CA_VERSION_DATA if * ] then echo "CA_RELESE $CA_RELEASE is invalid" exit -1 fi + source /etc/ncgl/ca_version_data ++ CA_PRODUCT_ID=samxts ++ CA_RELEASE=6 ++ CA_WEEK_NO=7 ++... (3 Replies)
Discussion started by: ketkee1985
3 Replies

7. Shell Programming and Scripting

process tree

how to draw a process tree if i know my process id and how can i identify session leaders (1 Reply)
Discussion started by: annapurna konga
1 Replies

8. Programming

error: initializer expression list treated as compound expression

I had seen this error for the first time ..... error: initializer expression list treated as compound expression please help.... (12 Replies)
Discussion started by: arunchaudhary19
12 Replies

9. UNIX for Dummies Questions & Answers

Binary Tree Creation Using fork()

Hi, I am working on a program and kind of a stuck,nt getting it done. "The program should take one command line arguments: number of hierarchy level. The hierarchy of your program should of that level and each node have two child processes." Can anyone give me the C code using fork() of this... (1 Reply)
Discussion started by: learneros
1 Replies

10. Shell Programming and Scripting

Regular Expression + Aritmetical Expression

Is it possible to combine a regular expression with a aritmetical expression? For example, taking a 8-numbers caracter sequece and casting each output of a grep, comparing to a constant. THX! (2 Replies)
Discussion started by: Z0mby
2 Replies
Login or Register to Ask a Question