user3847206
user3847206

Reputation: 21

Java add Tree to ArrayList

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.

Upvotes: 2

Views: 3624

Answers (2)

Chris
Chris

Reputation: 1742

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

Upvotes: 0

jatal
jatal

Reputation: 840

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

Upvotes: 1

Related Questions