12
返回列表 发新帖
楼主: yuanliu
跳转到指定楼层
上一主题 下一主题
收起左侧

热乎乎的狗家电面

🔗
 楼主| yuanliu 2018-11-26 12:15:58 | 只看该作者
全局:
暴雪私生子777 发表于 2018-11-25 06:46
第二道题目别的面试里面也有,请问是leetcode题目吗

思路可以类似于lowest common ancestor吧
回复

使用道具 举报

🔗
雨雪霏霏 2018-11-29 05:09:57 | 只看该作者
全局:
这个题因为不知道root 所以我感觉要先向上找a的ancestor, check 这个node是否也是b的ancestor(a/b反过来也一样)
check这一步也是dfs 所以写了两个dfs的function
一个用来找所有的ancestor
一个用来check
不知道思路对不对 求指点~求加米~

  1. class Node {
  2.         Node father;
  3.         Node mother;
  4.         List<Node> children;
  5.         public Node() {
  6.         father = new Node();
  7.         mother = new Node();
  8.         children = new LinkedList<>();
  9. }
  10. }

  11. boolean res = false;
  12. Set<Node> set = new HashSet<>();
  13. public boolean areRelative(Node a, Node b) {
  14.         getAncestor(a, b);
  15.         return res;
  16. }

  17. private void getAncestor(Node a, Node b) {
  18.         if (a == null) return;
  19.         if (res) return;
  20.         dfs(a, b);
  21.         getAncestor(a.mother, b);
  22.         getAncestor(a.father, b);
  23.         return;
  24. }
  25. // check all the ancestors of a
  26. // if one of them is ancestor of b, then they are relative
  27. private void dfs(Node a, Node b) {
  28.         if (res) return;
  29.         if (a == null || b == null) return;
  30.         if (set.contains(a)) return;
  31.        
  32.         if (a == b) {
  33.         res = true;
  34.         return;
  35. }

  36. for (Node n : a.children) {
  37.         dfs(n, b);
  38. }
  39. return;
  40. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表