dojoBeginner
dojoBeginner

Reputation: 449

converting a binary tree into List<List<Node>>

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

Answers (1)

Thomas
Thomas

Reputation: 88707

Assuming you want a list of nodes for each level, this seems to be correct, except:

  1. ol.put(level,il); List doesn't have a put method (it would be set in that case).
  2. I'd drop the line above and add a ol.add(il) after creating the new array list for the level.
  3. I'd also pass the outer list as a method parameter instead of using a member variable (although that's more of a design issue)
  4. There's a ; 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

Related Questions