# 剑指Offer Java版 面试题68：树中两个节点的最低公共祖先

### 参考答案

``````class TreeNode<T> {
T value;
List<TreeNode<T>> children;

public TreeNode(T value) {
this.value = value;
children = new ArrayList<>();
}
}

public <T> TreeNode<T> getLastCommonParent(TreeNode<T> root, TreeNode<T> node1, TreeNode<T> node2) {
if (root == null || node1 == null || node2 == null) {
return null;
}
getNodePath(root, node1, path1);
getNodePath(root, node2, path2);
return getLastCommonNode(path1, path2);
}

private <T> boolean getNodePath(TreeNode<T> root, TreeNode<T> node, LinkedList<TreeNode<T>> path) {
if (root == node) {
return true;
}
boolean found = false;
for (int i = 0; !found && i < root.children.size(); i++) {
found = getNodePath(root.children.get(i), node, path);
}
if (!found) {
path.removeLast();
}
return found;
}

Iterator<TreeNode<T>> iterator1 = path1.iterator();
Iterator<TreeNode<T>> iterator2 = path2.iterator();
TreeNode<T> last = null;
while (iterator1.hasNext() && iterator2.hasNext()) {
TreeNode<T> node = iterator1.next();
if (node == iterator2.next()) {
last = node;
} else {
break;
}
}
return last;
}
``````

### 复杂度分析

• 时间复杂度：O(n)。
• 空间复杂度：O(logn)。