店面第二问是应该这么写吗?- class Node {
- int val;
- List<Node> children;
- public Node(int val) {
- this.val = val;
- children = new ArrayList<>();
- }
- }
- class Solution {
- Set<Integer> vis = new HashSet<>(); // assuming unique val for all nodes
- private List<Integer>[] g;
- boolean isCyclic = false;
- public boolean validTree(List<Node> nodes) {
- g = new List[nodes.size()];
- Arrays.setAll(g, k -> new ArrayList<>());
- for (Node node : nodes) {
- for (Node child : node.children) {
- g[node.val].add(child.val);
- g[child.val].add(node.val);
- }
- }
- dfs(nodes.get(0));
- return vis.size() == nodes.size() && !isCyclic;
- }
- private void dfs(Node node) {
- vis.add(node.val);
- for (Node child : node.children) {
- if (!vis.contains(child.val)) {
- dfs(child);
- }
- else {
- isCyclic = true;
- return;
- }
- }
- }
- }
复制代码 |