我被这个问题偶然发现。以下是我的做法:给定节点对的最低公共祖先
Lets say the two nodes are node1 and node2
For any node (lets say node1), find the path from Root to
node1 and store it in an HashMap
For the other node node2, find the path from root to node2, and while traversing back,
check if any of the nodes are present in the hashmap or not
Return the first found node
时间复杂度为O(n)和空间复杂度也是O(h)时,其中n是树的高度
我只是想知道有多好,这种方法。或者是否存在其他更好的解决方案。
编辑:给定的树是二叉树,而不是BST。因此,查找节点所花的时间与节点的大小是线性的。
我的坏。给定的树是二叉树。我修改了我的帖子。谢谢 – 2010-10-24 20:57:54