0

I am getting a issue that my method is only returning the root node only as string. While it print the post order properly if i print the node in the helperPostOrder method.

public String postorder()
{
    return helperPostOrder(root, ""); // method calling
}

private String helperPostOrder(Node root , String s){
    if(root != null)
    {
        if(hasLeft(root)){
            helperPostOrder(root.left, s);
        }

        if(hasRight(root)){
            helperPostOrder(root.right, s);
        }
        s =  s + " " + root;
    }   

    return s;
}
1
  • Your recursive call helperPostOrder(root.left, s); is not modifying s, the value you are going to return. This is probably why you method is returning the root value without the left and right subtrees. Commented Apr 21, 2017 at 13:57

1 Answer 1

2

Can you try that? I dont have a compiler here but I think it is correct:

public String postorder()
{
    return helperPostOrder(root, ""); // method calling
}

private String helperPostOrder(Node root , String s){
    if(root != null)
    {
        if(hasLeft(root)){
            s = s + " " + helperPostOrder(root.left, s);
        }

        if(hasRight(root)){
            s = s + " " + helperPostOrder(root.right, s);
        }
    }   

    return s;
}

Added by @Ole V.V.: Your recursive call helperPostOrder(root.left, s); is not modifying s, the value you are going to return. This is probably why you method is returning the root value without the left and right subtrees.

Sign up to request clarification or add additional context in comments.

5 Comments

If my explanation in the comment under the question is correct, this should fix the issue. Your answer would benefit from explaining how and why…
updated with your explanation as I absolutely agree with it
I tried your given code but it is still not printing any thing.
In my given code string variable changes and append new nodes in the string variable until it reaches the last node of the tree from left side and recursive call for right nodes decrease the node form the string. and reached to the root node.
Oops, @gen.Strash, seems you forgot the line s = s + " " + root; in the code in your answer. Umar Ali, insert this in the same place it was in your code in the question, and you should be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.