Lowest Common Ancestor implementations - what's the difference?

此生再无相见时 提交于 2019-12-06 21:02:26

The LCA algorithm works for any tree (not necessarily binary and not necessarily balanced). Your "simple algorithm" analysis breaks down since tracing a path to a root node is actually O(N) time and space instead of O(log N)

Just want to point out that the problem is about the rooted tree and not binary search tree. So, in you algorithm the

O(n) time complexity for finding each of the 2 nodes, given the values O(n) space complexity for storing the path into the Set O(sqrt(n)) time complexity for going up the tree with the second node and searching in the first n-stored elements.

Checking of each node as we go up from the second node with take O(n), so for n nodes it will take O(sqrt(n)).

The Harel and Tarjan LCA algorithm (reference in the link you gave) uses a pre-calculation with O(n) complexity, after which a lookup is O(1) (not O(sqrt(n) as you claim).

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