c# - Replacing recursive with loop -
c# - Replacing recursive with loop -
i working on asp.net page, , there tree view in it. in tree view nodes have nested nodes branches. have info in list of custom objects in next format:
id, description, parentid
right now, using function recursively add together nodes tree view. next code snippet:
private bool findparentaddnode(string id, string description, string parentid, ref list<customtreenode> treelist) { bool isfound = false; foreach (customtreenode node in treelist) { if (node.id == parentid)//if current node parent node, add together in kid { node.addchild(id, description, parentid); isfound = true; break; } else if (node.listofchildnodes != null)//have kid nodes { isfound = findparentaddnode(id, description, parentid, ref node.listofchildnodes); if (isfound) break; } } homecoming isfound; }
the above technique works but, more 30k nodes, performance slow. please suggest algorithm replace recursive phone call loops.
as recurses downwards tree, code doing linear search on lists of kid nodes.
this means randomly distributed parent ids, after adding n nodes tree on average search n/2 nodes parent before adding n+1th node. cost o(n²) on number of nodes.
instead of linear scan, create index of id node , utilize find parent quickly. when create node , add together tree, add together dictionary<int,customtreenode>
. when want add together node parent, find parent in index , add together it. if addchild
returns kid creates, code becomes:
dictionary<int,customtreenode> index = new dictionary<int,customtreenode>(); private bool findparentaddnode(string id, string description, string parentid) { if ( !nodeindex.trygetvalue ( parentid, out parentnode ) ) homecoming false; index[id] = parentnode.addchild(id, description, parentid); homecoming true; }
you need add together root of tree index before using findparentaddnode
.
c# algorithm loops recursion
Comments
Post a Comment