算法总是美的,充满着magic.
一.前言
给定一棵树,同时给出树中的两个结点或者两个以上节点,求它们的最低公共祖先。这就是常见的LCA(Lowest Common Ancestor )问题。
二.两个节点的LCA问题
常规解法
1.1 思路
下面是一个简单的复杂度为 O(n) 的算法,解决LCA问题
1) 找到从根到n1的路径,并存储在一个向量或数组中。
2)找到从根到n2的路径,并存储在一个向量或数组中。
3) 遍历这两条路径,直到遇到一个不同的节点,则前面的那个即为最低公共祖先.
1.2 代码
//遍历两次,时间复杂度为O(n)
private static int findLCA(BinaryTree root, int key1, int key2) {
if (root == null) {
return -1;
}
List<Integer> path1 = new ArrayList<>();
List<Integer> path2 = new ArrayList<>();
boolean found1 = findPath(root,path1,key1);
boolean found2 = findPath(root,path2,key2);
int ans = 0;
if (found1 && found2) {
for (int i = 0; i < path1.size(); i++) {
if (path1.get(i) != path2.get(i)) {
break;
}else {
ans = path1.get(i);
}
}
return ans;
}
return -1;
}
/**
* @category 从根节点找到一条到指点数的路径.
* @param root 二叉树根节点
* @param path 存储