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:
ol.put(level,il);
list doesn't have put method (itset
in case).- i'd drop line above , add
ol.add(il)
after creating new array list level. - i'd pass outer list method parameter instead of using member variable (although that's more of design issue)
- there's
;
missing afterbuild(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
Post a Comment