Build tree from edges

与世无争的帅哥 提交于 2019-12-06 13:52:47

@mirt thanks for pointing out the optimizations on my approach, have you got any better? i will put the below algo for ref

initially construct a hash map to store elements that are there in tree : H, add the root (null in your case/ or anything that represent that root)

taking the pair (_child, _parent)

  1. loop through the whole list. in the list. (each pair is the element)
  2. for each pair, see if the _child and _parent is there in the hash map H, if you dont find, create the tree node for the missing ones and add them to H , and link them with the parent child relationship.
  3. you will be left with the tree at the end of iteration.

complexity is O(n).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!