I have to make a class for a binary search tree for a school assignment, and one of the methods I must implement is going to return a string of all the leaf node values, separated by a comma, like this ["Leaf node 1",Leaf node 2, Leaf node 3]. Going from left to right.
I have to solve this using a recursive helping method, and I'm totally blank
This is what I have so far
public void leafNodes(Node<T> n)
{
if(n.left != null) leafNodes(n.left);
if(n.right != null) leafNodes(n.right);
if(n.left == null && n.right == null)
{
// Do something in here?
}
}
Tried editing after suggestion:
I tried adding it like this:
public ArrayList<String> leafNodes(Node<T> n)
{
ArrayList<String> list = new ArrayList<>();
if(n.left != null) leafNoder(n.left);
if(n.right != null) leafNoder(n.right);
if(n.left == null && n.roight == null)
{
list.add(n.value.toString());
}
return list;
}
The method that takes use of this helping method now return an empty string. Or just the "[]".
public String LeafNodeValues()
{
StringJoiner sj = new StringJoiner(", ", "[","]");
if(empty()) return sj.toString();
ArrayList<String> a = leafNodes(rot);
for(int i = 0; i < a.size(); i++)
{
sj.add(a.get(i));
}
return sj.toString();
}
Like this?
public ArrayList<String> leafNodes(Node<T> n)
{
ArrayList<String> list = new ArrayList<>();
if(n.left != null) list.addAll(leafNoder(n.left));
if(n.right != null) list.addAll(leafNoder(n.right));
if(n.left == null && n.roight == null)
{
list.add(n.value.toString());
}
return list;
}