Find Root of N-Ary Tree
给一个用list表示的n-ary tree. 求这个tree的node是哪个node.
这个题主要是理解题意, 人家是让找那个node是root, 所以看root的特性是: root肯定不是任何node的children. 用set查找即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() { children = new ArrayList<Node>(); } public Node(int _val) { val = _val; children = new ArrayList<Node>(); } public Node(int _val,ArrayList<Node> _children) { val = _val; children = _children; } }; */ class Solution { public Node findRoot(List<Node> tree) { Set<Node> set = new HashSet<>(); for(Node t : tree){ set.addAll(t.children); } for(Node n : tree){ if(!set.contains(n)) return n; } return null; } } |