Monday, August 23, 2010

building tree view from given child-parent pairs in hashmap

Ex: The child-parent pairs are in a hashmap 'childParentMap' as shown below. The root node is with value 0.
1 -> 0
2 -> 1
3 -> 2
4 -> 2
5 -> 0

node:
    id
    nodes children

node (childparentmap):
    root = null
    idnodemap = new
    for childid, parentid in childparentmap:
        if idnodemap.has(childid):
            child = idnodemap[childid]
        else:
            child = new (childid)
            idnodemap[childid] = child
        if idnodemap.has(parentid):
            parent = idnodemap[parentid]
        else:
            parent = new (parentid)
            idnodemap[parentid] = parent
        parent.addchild(child)
        if parent.id == 0:
            root = parent
    return root
Time is O(n).
There is a recursive solution too but it takes O(n^2) time.
The code is similar to building a graph from an adjacency list.

[H/T ai, as, sc, jf, se]

No comments:

Post a Comment