Wayfair
  • OA
    • Karat
      • 811. Subdomain Visit Count
      • Ads Conversion Rate
      • Recommend Movie
      • Longest Common Continuous Subarray
      • Course Overlap
      • Halfway courses
      • Find one rectangle
      • Find all rectangles
      • Find Multiple Shapes
      • word wrap
      • word processor
      • Basic Calculator
      • Basic Calculator with parenthesis
      • 带变量计算器
      • Valid Matrix
      • nonogram
      • Node with 0 or 1 parents
      • 两个节点是否有公共祖先
      • 最远祖先
      • invalid Badge Records
      • 一小时内access多次
      • canSchedule
      • spareTime
      • sparse vector
      • sparse vector 实现add,dot和cos
      • userlogs earliest and latest access time
      • resource Access with in 5 min
      • Find Word Path in Grid
      • Find legal moves
      • 找能去的所有0区域
      • 最短路径找treasure
  • VO
    • Coding
      • Valid Palindrome
      • Add String
      • Coupon
    • System design
    • BQ
    • OOD
  • SD
  • LeetCode Tag
  • VO Onsite
Powered by GitBook
On this page
  1. OA
  2. Karat

两个节点是否有公共祖先

 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;
    }
PreviousNode with 0 or 1 parentsNext最远祖先

Last updated 3 years ago