Naina kathuria
Naina kathuria

Reputation: 1

Inorder traversal of expression tree in java

I am creating inorder traversal of expression tree but it is not considering the middle element. Below is my code. Can you please let me know where i am wroong and code i have missed. e.g if the prefix notation of expression tree is * 1 + 2 3 then the output of inorder tree along with paranthesis should be (1+(2*3)) but i am getting output (1(23)+)*

public String toStringPrettyInFix(){

    return printInorder(root)+")";

}

String printInorder(FCNSTreeNode root)
{

    String s="";
    if (root == null)
        return "";

    if(root.firstChild!=null) {


        s=s+"("+printInorder(root.firstChild);

    }     



    if(root.nextSibling!=null) {
        s=s+printInorder(root.nextSibling)+")";

    }


System.out.println(s);

    return s;

}

Upvotes: 0

Views: 537

Answers (1)

Abhishek Singh
Abhishek Singh

Reputation: 246

In order traverse left then visit middle then go right.Here you missed the middle part

if(root.firstChild!=null) {


    s=s+"("+printInorder(root.firstChild);

}     

s = s+root.value //value is whatever stored in node 

if(root.nextSibling!=null) {
    s=s+printInorder(root.nextSibling)+")";

}

Upvotes: 1

Related Questions