Lowest Common Ancestor II
For the following binary tree:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7 For the following binary tree:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7 public class Solution {
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*/
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root,
ParentTreeNode A,
ParentTreeNode B) {
List<ParentTreeNode> lstA = new ArrayList<>();
List<ParentTreeNode> lstB = new ArrayList<>();
ParentTreeNode temp = A;
while (temp != null) {
lstA.add(temp);
temp = temp.parent;
}
temp = B;
while (temp != null) {
lstB.add(temp);
temp = temp.parent;
}
int len = Math.min(lstA.size(), lstB.size());
for (int i = 0; i < len; ++i) {
if (lstA.get(lstA.size() - 1) == lstB.get(lstB.size() - 1)) {
temp = lstA.remove(lstA.size() - 1);
lstB.remove(lstB.size() - 1);
}
}
return temp;
}
} class Solution:
"""
@param root: The root of the tree
@param A and B: Two node in the tree
@return: The lowest common ancestor of A and B
"""
def lowestCommonAncestorII(self, root, A, B):
if A == B:
return A
lstA = []
lstB = []
while A:
lstA.append(A)
A = A.parent
while B:
lstB.append(B)
B = B.parent
temp = root
length = min(len(lstA), len(lstB))
for i in range(length):
if lstA[-1] == lstB[-1]:
temp = lstA.pop()
lstB.pop()
return temp class Solution:
"""
@param: root: The root of the tree
@param: A: node in the tree
@param: B: node in the tree
@return: The lowest common ancestor of A and B
"""
def lowestCommonAncestorII(self, root, A, B):
st = set()
while A:
st.add(A)
A = A.parent
while B:
if B in st:
return B
B = B.parent public class Solution {
/*
* @param root: The root of the tree
* @param A: node in the tree
* @param B: node in the tree
* @return: The lowest common ancestor of A and B
*/
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root, ParentTreeNode A, ParentTreeNode B) {
Set<ParentTreeNode> set = new HashSet<>();
while (A != null) {
set.add(A);
A = A.parent;
}
while (B != null) {
if (set.contains(B)) return B;
B = B.parent;
}
return null;
}
}