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 {
ArrayList<LinkedList<Node>> makeArrayList(Node n) {
int level = 0;
return addLists(new ArrayList<LinkedList<Node>>(), n, level);
}
ArrayList<LinkedList<Node>> addLists(ArrayList<LinkedList<Node>> arr, Node n, int level) {
if (n != null) {
if (arr.get(level) == null) {
LinkedList<Node> newList = new LinkedList<Node>();
arr.add(level, newList);
}
LinkedList<Node> nodeList = arr.get(level);
nodeList.add(n);
addLists(arr, n.leftChild, level + 1);
addLists(arr, n.rightChild, level + 1);
}
return arr;
}
}
I haven't test it
then do it. – tb- Mar 1 at 22:32