Hello everyone, I am trying to devise a Binary Tree Representation of a Postfix Expression. I am sure I am in the right track, but there's just something wrong in my code which I cannot find.

I am just wondering if you guys can spot where I made my mistake. I would really appreciate your help.

I am using a Dev-C++ compiler.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>

struct node{
			char item;
			struct node* leftChild;
			struct node* rightChild;
			};
			
typedef struct node node; 
node* root;

static node* stack[25];
static int stackPtr = -1;

node* pop(void)
{
	return(stack[stackPtr--]);
}

void push(node* root)
{
	stack[++stackPtr] = root;
}

void operator(char optr)
{
    root = (node*)malloc(sizeof(node));
	root->item = optr;
	root->rightChild = pop();
	root->leftChild = pop();
	push(root);
}

void operand(char opnd)
{
    root = (node*)malloc(sizeof(node));
	root->item = opnd;
	root->rightChild = NULL;
	root->leftChild = NULL;
	push(root);
}

void PostTraverse (node* root)
{
	if (root->leftChild != NULL) {
		PostTraverse (root->leftChild);
    }
	if (root->rightChild != NULL) {
		PostTraverse (root->rightChild);
    }
	printf("%c ", root->item);
}

int main (void)
{
    char postfix[] = "1 2 + 4 * 5 7 - +";
    char *token;
    int i = 0;

    token = strtok(postfix, " ");
    while (token != NULL) {
        if(token !='('&& token !=')'&& token !='^'&& token !='*'&&
token !='/'&& token !='+'&& token !='-')
        {
         operand(token);
        } else {
               operator(token);
        }                                                                                                             
        token = strtok(NULL, " ");
    }
    PostTraverse(stack);
    printf("\n");
    system("pause");
    return 0;
}

One problem I found is that the operator() function is like being ignored in the program and I don't know why that was happening. Any idea?

Thank you very much.

Why is root a global variable? As far as I can see, it doesn't need to be, and it's just causing confusion because several functions take a root parameter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.