Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 03:29
Show Gist options
  • Save charlespunk/4707736 to your computer and use it in GitHub Desktop.
Save charlespunk/4707736 to your computer and use it in GitHub Desktop.
Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth(e.g., if you have a tree with depth D, you'll have D linked lists).
public static ArrayList<LinkedList<Node>> createNodeLists(Node root){
ArrayList<LinkedList<Node>> nodeLists = new ArrayList<LinkedList<Node>>();
LinkedList<Node> thisList = new LinkedList<Node>();
if(root != null) thisList.add(root);
while(!thisList.isempty()){
nodeLists.add(thisList);
LinkedList<Node> sons = new LinkedList<Node>();
for(Node n: thisList){
if(n.left != null) sons.add(n.left);
if(n.right != null) sons.add(n.right);
}
thisList = sons;
}
return nodeLists;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment