2

Im trying to add each node of a Binary Search Tree to an ArrayList in order, I currently have this code...

private ArrayList<String> toArray(TreeNode<Comparable> root)
  {    
    ArrayList<String> array = new ArrayList<String>();
    if(root!= null)
      return null;
    inorder(root.getLeft());
    array.add(root.getValue());
    inorder(root.getRight());
    return array;
  }

but i get this error from running it...

Error: BSTree.java:64: cannot find symbol
symbol  : method add(java.lang.Comparable)
location: class java.util.ArrayList<java.lang.String>

thank you for any help.

4
  • What does your TreeNode class look like? Commented May 29, 2015 at 0:14
  • 1
    This method takes a tree of Comparable:s - there are a lot of Comparable:s that aren't Strings. Only Strings fits into the ArrayList. See? Commented May 29, 2015 at 0:16
  • how do i add comparables to an arraylist Commented May 29, 2015 at 0:18
  • 1
    ArrayList<String> -> ArrayList<Comparable> Commented May 29, 2015 at 0:18

2 Answers 2

1

Would the following Generic method work for you? I'm away from my compiler but solution should be something like this:

  private <T extends Comparable<T>> ArrayList<T> toArray(TreeNode<T> root)
  {    
    if(null == root)
      return null;

    ArrayList<T> array = new ArrayList<T>();
    inorder(root.getLeft());
    array.add(root.getValue());
    inorder(root.getRight());
    return array;
  }

This TreeNode seems similar to the class in this webpage: Some CS Class notes

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

Comments

0

I have used something like this

private void inorder(Node u){
            if( tree.isLeaf(u) ){
                arrayList.add(u);
            }else{
                Node v = tree.getLeft(u);
                invorder(v);

                arrayList.add(u);

                v = tree.getRight(v);
                invorder(v);
}

Comments

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.