0

I want to make an in order transversal of a binary tree. I made this method:

public String inorder()
    {
        String inorder = "";
        return recrInorder(this.root, inorder);
    }

then i have a helper method:

private String recrInorder(Node curr,String string)
    {
        if(curr == null)
        {
            return "";
        }
        //Go through left
        recrInorder(curr.getLeft(), string);
        string = string + curr.getData() + ", ";
        //Go through right
        recrInorder(curr.getRight(), string);
        return string;
    }

This will only print the root, i want the whole list printed.

3 Answers 3

3

In Java parameters are passed by value for object reference so assigning new value to your input parameter named string will not change its value outside of that function.

You need to change your code like this

private String recrInorder(Node curr,String string)
{
    if(curr == null)
    {
        return string; // preserve previously calculated value
    }
    //Go through left
    string = recrInorder(curr.getLeft(), string);
    string = string + curr.getData() + ", ";
    //Go through right
    string = recrInorder(curr.getRight(), string);
    return string;
}
Sign up to request clarification or add additional context in comments.

Comments

2
public String inorder() {
    return recrInorder(this.root);
}
private String recrInorder(Node curr) {
    if (curr == null) return "";
    return recrInorder(curr.getLeft()) + curr.getData() + ", " + rectInorder(curr.getRight());
}

Comments

0

Given a parent, left child, and right child relationship, the traversal of the tree is dependent on when you visit the parent and access the String value.

Given the root of the tree call it as follows:

    String s =  traverse(root, "");
    System.out.println(s);
    public static String traverse(Node n, String s) {
        if (n == null) {
            return s;
        }
        // s += n.value;  // uncomment this assignment for preorder traversal
        s = traverse(n.left,s);
        // s += n.value;  // uncomment this assignment for inorder traversal
        s = traverse(n.right,s);
        // s += n.value;  // uncomment this assignment for postorder traversal
        return s;
    }

So in your method, you could pass a flag or enum and caveat the assignment based on that value, thus adapting your method to any traversal.

Comments

Your Answer

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