题意:输入一个二叉查找树(BST),和两个给定节点,在BST中找到这两个节点的最低的共同的祖先(LCA)。
温馨提示:wiki对LCA的定义为两个节点的最低的祖先,即两个节点到根的首个交点,LCA用在树(计算两个节点之间的距离,即两个节点到根距离的和减去2被的LCA)或者有向无环图。
思路:1、节点的层次,其中,根节点的层次是父节点层次加1(递归定义);
2、使用HashMap建立节点与直接父节点之间的映射;
3、两个节点的LCA必定高度相同,使用数据结构stack出栈操作求出LCA。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
HashMap
lineage = new HashMap<>();
lineageGen(root, lineage);
ArrayList
stackForP = new ArrayList<>();
ArrayList
stackForQ = new ArrayList<>();
pathGen(stackForP, p, lineage);
pathGen(stackForQ, q, lineage);
int depth1 = stackForP.size(), depth2 = stackForQ.size();
int index = (depth1 < depth2) ? depth1 : depth2;
for(int i = 0; i < index; i++){
TreeNode tmpForP = stackForP.get(depth1 - index + i);
TreeNode tmpForQ = stackForQ.get(depth2 - index + i);
if(tmpForP.equals(tmpForQ)){
return tmpForP; //必然返回
}
}
return root;
}
//O(树的深度)
private void pathGen(ArrayList
stackForP, TreeNode p, HashMap
lineage) { TreeNode tmp = p; stackForP.add(tmp); while((tmp = lineage.get(tmp)) != null){ stackForP.add(tmp); } } //O(n) private void lineageGen(TreeNode root, HashMap
lineage) {//O(n)不包括root映射 if(root.left != null){ lineage.put(root.left, root); lineageGen(root.left, lineage); } if(root.right != null){ lineage.put(root.right, root); lineageGen(root.right, lineage); } }