Created
March 12, 2013 19:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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