Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created March 12, 2013 19:54
Show Gist options
  • Save Ray1988/5146396 to your computer and use it in GitHub Desktop.
Save Ray1988/5146396 to your computer and use it in GitHub Desktop.
4.4 given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth
void createLinkedListFromBT(TreeNode r,ArrayList al, int level){
if(r==null) return;
LinkedList<TreeNode> temp=null;
if(al.size()==level){
temp=new LinkedList<TreeNode>();
al.add(temp);
}else if(level<al.size()){
temp=al.get(level)
}
else{
return;
}
temp.add(r);
createLinkedListFromBT(r.left,al, level+1);
createLinkedListFromBT(r.right,al, level+1);
}
ArrayList<LinkedList<TreeNode>> createLinkedlist(TreeNode r){
if(r!=null){
ArrayList<LinkedList<TreeNode>> al=new Arraylist<LinkedLis<TreeNode>>();
createLinkedListFromBT(r, al, 0);
return al;
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment