我被這個問題偶然發現。以下是我的做法:給定節點對的最低公共祖先
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