活跃农民
- 积分
- 397
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-3-21
- 最后登录
- 1970-1-1
|
这个题因为不知道root 所以我感觉要先向上找a的ancestor, check 这个node是否也是b的ancestor(a/b反过来也一样)
check这一步也是dfs 所以写了两个dfs的function
一个用来找所有的ancestor
一个用来check
不知道思路对不对 求指点~求加米~
- class Node {
- Node father;
- Node mother;
- List<Node> children;
- public Node() {
- father = new Node();
- mother = new Node();
- children = new LinkedList<>();
- }
- }
- boolean res = false;
- Set<Node> set = new HashSet<>();
- public boolean areRelative(Node a, Node b) {
- getAncestor(a, b);
- return res;
- }
- private void getAncestor(Node a, Node b) {
- if (a == null) return;
- if (res) return;
- dfs(a, b);
- getAncestor(a.mother, b);
- getAncestor(a.father, b);
- return;
- }
- // check all the ancestors of a
- // if one of them is ancestor of b, then they are relative
- private void dfs(Node a, Node b) {
- if (res) return;
- if (a == null || b == null) return;
- if (set.contains(a)) return;
-
- if (a == b) {
- res = true;
- return;
- }
- for (Node n : a.children) {
- dfs(n, b);
- }
- return;
- }
复制代码 |
|