两个节点是否有公共祖先
public boolean hasCommonAncestor(int[][] edges, int x, int y)
{
if (edges == null || edges.length == 0) {
return false;
}
Map<Integer, Set<Integer>> map = new HashMap<>();
for(int i = 0; i< edges.length; i++)
{
int parent = edges[i][0];
int child = edges[i][1];
map.putIfAbsent(child, new HashSet<Integer>());
map.get(child).add(parent);
}
Set<Integer> parentOfX = findAllParents(map, x);
Set<Integer> parentOfY = findAllParents(map, y);
for(Integer parentX : parentOfX)
{
if(parentOfY.contains(parentX))
{
return true;
}
}
return false;
}
public Set<Integer> findAllParents(Map<Integer, Set<Integer>> map, int node)
{
Set<Integer> parents = new HashSet<>();
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(node);
while(!queue.isEmpty())
{
int current = queue.poll();
for(Integer nextElement : map.get(current))
{
queue.offer(nextElement);
if(!parents.contains(nextElement))
{
parents.add(nextElement);
}
}
}
return parents;
}
Last updated