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


is 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); } 

assuming want list of nodes each level, seems correct, except:

  1. ol.put(level,il); list doesn't have put method (it set in case).
  2. i'd drop line above , add ol.add(il) after creating new array list level.
  3. i'd pass outer list method parameter instead of using member variable (although that's more of design issue)
  4. there's ; missing after build(root, 0)

edit: clarify no. 2:

if(ol.size() < level) {   il = new arraylist<node>();   ol.add(il); //add here only, assuming level = ol.size() + 1 true in case } 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -