4
public class Node {
private int data;

public int getData() {
    return data;
}

private Node left;
private Node right;

public Node(int d, Node l, Node r) {
    data = d;
    left = l;
    right = r;
}

// Deep copy constructor
public Node(Node o) {
    if (o == null) return;
    this.data = o.data;
    if (o.left != null) this.left = new Node(o.left);
    if (o.right != null) this.right = new Node(o.right);
}

public List<Integer> toList() {
// Recursive code here that returns an ordered list of the nodes
}

The full class is here: https://pastebin.com/nHwXMVrd

What recursive solution could I use to return an ordered ArrayList of the Integers inside the Node? I've tried a lot of things but I have been having difficulties to find a recursive solution.

ismael oliva
  • 97
  • 1
  • 3
  • 11

2 Answers2

1

Given that you have a bst you can make an inorder traversal on in, this will give you all the elements in increasing order (sorted), an example of how it's done:

 public List<Integer> toList() {
        return createOrderedList(this);
 }

 private List<Integer> createOrderedList(Node root) {
     if(root == null) {
         return new ArrayList<>();
     }

     List<Integer> list = new ArrayList<>();
     list.addAll(createOrderedList(root.left));
     list.add(root.data);
     list.addAll(createOrderedList(root.right));

     return list;
 }
Schidu Luca
  • 3,897
  • 1
  • 12
  • 27
  • `return new ArrayList` *or* `Collections.emptyList()`, you should also pin to your answer that this is using recursion, which for a lot of nodes... – Eugene Feb 28 '18 at 10:10
  • Nice point. About recursion though, I don't think it's a big deal. The maximum number of calls in kept in stack is equal to the height of the tree, which in most cases is somewhat `nlogn`, (unless it's very unbalanced). So you need reaaally big tree to get a `Stackoverflow`, if that was your point. – Schidu Luca Feb 28 '18 at 11:00
0

I am not profficent in Java but this would be the general idea of doing it:

public List<Integer> toList() 
{
   List<Integer> newList = new List<Integer>();
   newList.add(this.data);
   if(left != null)
      newList.addAll(left.toList());
   if(right != null)
      newList.addAll(right.toList());
   return newList;
}
Robert
  • 2,407
  • 1
  • 24
  • 35
  • Brilliant, and I will add Collections.sort(newList); Just to order the list. Looking forward for more efficient solutions! My professor said there is a way to automatically order the list without collections! Thanks. – ismael oliva Feb 28 '18 at 09:18
  • 1
    To obtained a ordered list just put this line ```newList.add(this.data);``` after the first ```if```. It will be an inorder traversal :) – Schidu Luca Feb 28 '18 at 12:12