# Creating an Array of Linked Lists from a BST

Question

Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)

Here is my attempt at a solution. I haven't test it, but I was trying to get feedback on whether or not this would be an appropriate approach to such solution.

public class solution {

int level = 0;
}

if (n != null) {
if (arr.get(level) == null) {
}
}
return arr;
}
}

• I haven't test it then do it. – tb- Mar 1 '13 at 22:32

This section:

if (arr.get(level) == null) {
}


is going to throw an IndexOutOfBoundsException every single time, since you never do arr.add before doing arr.get. The proper way to do it (incorporating some good suggestions from @mnhg's answer):

{
if (n == null) return arr;

return arr;
}


This, of course, is why we test code before sending it for review.

Your return types and the types left of the assignments should be as general as possible, so you only need to change the instantiation if you want to change the implementation to an other type of list.

List<Node>
List<List<Node>>


In general it is a good idea to replace ifs that covers the whole function by a guard condition. So you get rid of a level of nesting.

{
if (n == null) return arr;

return arr;
}


I only checked your code layout. If you want to see if it works, write a test as tb suggested.