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 rootTime 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