0

I'm working on a Path method that returns the path from the given node to the node with the key of a given value. My code returns the correct numbers, but they are inside a bracket. How do I remove the bracket?

 private boolean pathhelp(Node n, int val, ArrayList<Integer> lst){
    if(n == null){
        return false;
    }else if(val < n.key){
        lst.add(n.key);
        return pathhelp(n.left, val, lst);
    }else if(val > n.key ){
        lst.add(n.key);
        return pathhelp(n.right, val, lst);
    }else{
        lst.add(n.key);
        return true;
    }
  }
   public String path(Node node, int value) {
    ArrayList<Integer> path = new ArrayList<Integer>();

    if(pathhelp(root,value,path) == true ){
        System.out.println(path);
        String p = "";
        //build p from path list

        return p;
    }else{
        return "";
    }
 }
  }

The actual output is:

[6, 5, 1, 4]

But it is supposed to be:

6, 5, 1, 4
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
liiu
  • 31
  • 1
  • 5

1 Answers1

0

Something like that for example (using Java 8 Streams):

import java.util.*;
import java.util.stream.Collectors;

class Scratch {

    public static void main(String[] args) {
        ArrayList<Integer> path = new ArrayList<Integer>();
        path.add(1);
        path.add(2);

        String asString = path.stream()
                                    .map(Object::toString)
                                    .collect(Collectors.joining(", "));

        System.out.println(asString);
    }
}

You may also use Guava's Joiner

Pavel S.
  • 1,267
  • 14
  • 19