解题思路一:
DFS到每个节点的路径,根据路径算出LCA:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == p || root == q)
return root;
List pList = new ArrayList<TreeNode>(), qList = new ArrayList<TreeNode>();
getPath(root,p,pList);
getPath(root,q,qList);
for(int i=0;i<Math.min(pList.size(), qList.size());i++){
if(pList.get(i)!=qList.get(i))
return (TreeNode) pList.get(i-1);
}
return (TreeNode) pList.get(Math.min(pList.size(), qList.size())-1);
}
private boolean getPath(TreeNode root, TreeNode p, List<TreeNode> path) {
path.add(root);
if (root == p)
return true;
if (root.left != null) {
if (getPath(root.left, p, path))
return true;
path.remove(path.size() - 1);
}
if (root.right != null) {
if (getPath(root.right, p, path))
return true;
path.remove(path.size() - 1);
}
return false;
}
}
解题思路二:
后续遍历+并查集(《数据结构》第11章内容),实现的时间空间,复杂度略高
解题思路三:并查集+Tarjan算法
参考:http://baike.baidu.com/link?url=oJBohljiyLYv4B0lFr5nbXOeYQ6B1PD4jAYAAZ0v2jKWR_ygiKyNFYqfIgWYbST0meiByvGTFNEjftX7vst90q#3_1