Construct expression tree | Practice | GeeksforGeeks

Given a postfix expression. Your task is to complete the method constructTree(). The output of the program will print the infix expression of the given postfix expression.

Input:
The constructTree() function takes a single argument as input, character array containing the given postfix expression.
Output:
Infix expression should be printed for each given postfix expression.
Constraints:
1<=T<=50
1<=length_of_expression<=40
Example:
Input:
2
ab+ef*g*-
wlrb+-*
Output:
a + b - e * f * g
w * l - r + b
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
+1
jagjiwan4 months ago
et* constructTree(char postfix[]){
    stack<et*> stk;

    for(int i=0;postfix[i]!='\0';i++){
        char ch=postfix[i];
        et* node=new et(ch);
        
        if(ch=='*' || ch=='/' || ch=='+' ||
           ch=='-' || ch=='^'){
            node->right=stk.top();
            stk.pop();
            node->left=stk.top();
            stk.pop();
        }
        
        stk.push(node);
    }
    return stk.top();
}
0
sarkarrohit650
This comment was deleted.
+8
soham36chowdhury4 months ago
Approach using Stack in C++
We traverse the postfix expression and create nodes whenever we encounter non-operators.
We store these nodes in stack data structure.
Whenever we encounter an operator, we pop the top 2 elements of our stack and assign them as left and right nodes to the current operator. Then we push this node structure to our stack.
Hence, iteratively we keep on growing our tree structure and at the end there will always be only a single element in the stack , pointing the head of our expression tree.
We return the head.
 

et* constructTree(char postfix[])
{
//code here
stack<et*> st;
int n=strlen(postfix);
for(int i=0;i<n;i++){
   if(isalpha(postfix[i])){
       et *node = (struct et *)malloc(sizeof(struct et)); //new node allocation
           node->value = postfix[i];
           node->left = 0;
           node->right = 0;
           st.push(node);
   }
   else
   {et *node1,*node2,*node3;
           node3 = (struct et *)malloc(sizeof(struct et));
           node3->value = postfix[i];
           node2 = st.top();
           node3->right = node2;
           st.pop();
           node1 = st.top();
           node3->left = node1;
           st.pop();
           st.push(node3);}
           
}
return st.top();
}
 
+2
gowthamreddyuppunuri4 months ago
Very easy stack solution
bool isOperand(char ch){
   return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
et* constructTree(char postfix[])
{
//code here
    // conversion of postfix to infix is easy using stack
    // but tree construction can be done similarlly building it from bottom
    stack<string> st;
    stack<et*> treeStack;
    // int len = *(&postfix+1)-postfix;//not worked
    // int len = sizeof(postfix)/sizeof(postfix[0]);//not worked
    // int len = strlen(postfix);//fuck getting size

    for(int i=0; postfix[i] != '\0'; i++){
        if(isOperand(postfix[i])){
            string op(1,postfix[i]);
            et *newNode = new et(postfix[i]);
            treeStack.push(newNode);
            st.push(op);
        }
        // assuming correct postfix exp, there is operator after every two operands
        else{
            string op1 = st.top(); st.pop();
            string op2 = st.top(); st.pop();
            string op = op2+" "+postfix[i]+" "+op1;
            // construct tree pointer to this new expression
            et *rightNode = treeStack.top(); treeStack.pop();
            et *leftNode = treeStack.top(); treeStack.pop();
            et *rootNode = new et(postfix[i]);
            rootNode->left = leftNode; rootNode->right = rightNode;
            treeStack.push(rootNode);
            st.push(op);
        }
    }
    string ans = st.top(); st.pop();
    // cout<<ans<<"\n";
    et *finalRoot = treeStack.top(); treeStack.pop();
    // return ans;
    return finalRoot;
}
+5
fungkwe4 months ago
Very easy using a stack.
0
zimmychang5 months ago
et* constructTree(char postfix[])
{
//code here
stack<et *> s;
    for (int i = 0; i < strlen(postfix); i++)
    {
        if (isalpha(postfix[i]))
        {
            et *node = (struct et *)malloc(sizeof(struct et));
            node->value = postfix[i];
            node->left = 0;
            node->right = 0;
            s.push(node);
        }
        else
        {
            et *node1,*node2,*node3;
            node3 = (struct et *)malloc(sizeof(struct et));
            node3->value = postfix[i];
            node2 = s.top();
            node3->right = node2;
            s.pop();
            node1 = s.top();
            node3->left = node1;
            s.pop();
            s.push(node3);
        }
    }
    return s.top();
}
+1
anutiger6 months ago
et *helper(string s,int l,int h){
    if(l > h)
        return NULL;
    int mid = (l + h) / 2;
    et *res = new et(s[mid]);
    if(l == h)
        return res;
    res->left = helper(s,l,mid - 1);
    res->right = helper(s,mid + 1,h);
    return res;
}
et* constructTree(char postfix[])
{
    char c = 'a';
    string res = "";
    stack<string> st;
    int size = strlen(postfix);
    for(int i = 0;i < size ; i ++){
        if(isalpha(postfix[i])){
            string s = "";
            s += postfix[i];
            st.push(s);
        }
        else{
            string temp = "";
            temp += st.top();st.pop();
            temp = postfix[i] + temp;
            temp = st.top() + temp;st.pop();
            st.push(temp);
        }
    }
    while(!st.empty()){
        res = st.top() + res;st.pop();
    }
    return helper(res,0,res.length());
}
0
Dhruv Mishra_18267 months ago
Dhruv Mishra_1826
et* constructTree(char a[]){//code hereint n=strlen(a),i;stack<et*> st;//st.push(root);
for (i=0; i<n; i++){="" if="" (isalpha(a[i])){="" et*="" p="new" et(a[i]);="" st.push(p);="" }="" else{="" et*="" p="new" et(a[i]);="" p-="">right=st.top();        st.pop();        p->left=st.top();        st.pop();        st.push(p);    }}
    return st.top();}
0
Madhav Chittlangia8 months ago
Madhav Chittlangia
Java Solutionclass GfG{static  boolean isOperator(char c){if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^'){return true;}return false;}public static Node constructTree(char postfix[]){Stack<node> stack = new Stack<>();for(int i=0; i<postfix.length; i++){="" if(!isoperator(postfix[i])){="" node="" t="new" node(postfix[i]);="" stack.push(t);="" }="" else{="" node="" t="new" node(postfix[i]);="" node="" t1="stack.pop();" node="" t2="stack.pop();" t.left="t2;" t.right="t1;" stack.push(t);="" }="" }="" return="" stack.pop();="" }="" }<="" code="">
0
kartikeya Sharma8 months ago
kartikeya Sharma
et* constructTree(char p[]){    int n = strlen(p);    stack<et*> s;     for(int i = 0 ; i < n ; i++)    {        if(isOperator(p[i]))        {            et* right = s.top();s.pop();            et* left =  s.top();s.pop();            et* temp = new et(p[i]);            temp->left = left;            temp->right = right;            s.push(temp);        }        else        {         s.push(new et(p[i]));           }    }    return s.top();}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.