Muhammad Umar
Muhammad Umar

Reputation: 130

Issue with returning post order expression of tree using recursion in java

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;
}

Upvotes: 0

Views: 270

Answers (1)

strash
strash

Reputation: 1321

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.

Upvotes: 2

Related Questions