Reputation: 449
IS my algorithm correct?
List<List<Node> > ol = new ArrayList<List<Node>>();
build(root,0)
void build (Node node,int level)
{
if(node==null)
return;
List<Node> il;
if(ol.size() < level){
il = new ArrayList<Node>();
}else{
il= ol.get(level);
}
il.add(node);
ol.put(level,il);
build(node.left, level+1);
build(node.right,level+1);
}
Upvotes: 0
Views: 1135
Reputation: 88707
Assuming you want a list of nodes for each level, this seems to be correct, except:
ol.put(level,il);
List doesn't have a put method (it would be set
in that case).ol.add(il)
after creating the new array list for the level.;
missing after build(root, 0)
Edit: to clarify no. 2:
if(ol.size() < level) {
il = new ArrayList<Node>();
ol.add(il); //add here only, assuming level = ol.size() + 1 always is true in this case
}
Upvotes: 1