首页 > 代码库 > Build Relationship Tree
Build Relationship Tree
import java.util.*; class Node{ String val; Set<Node> children = new HashSet<Node>(); // at most 15 children; public Node(String val){ this.val = val; this.children = new HashSet<>(); } } public class RelationTree { private void travel(Node root){ System.out.println(root.val); for(Node n: root.children){ travel(n); } } private Node findRelations(String[] input) { // TODO Auto-generated method stub HashMap<String, Node> map = new HashMap<String, Node>(); Set<String> childrenSet = new HashSet<String>(); for(int i = 0 ; i < input.length - 2 ; i++){ String manager = input[i].split("->")[0]; String person = input[i].split("->")[1]; Node managerNode = new Node(manager); Node personNode = new Node(person); childrenSet.add(person); if(map.containsKey(manager)){ if(map.containsKey(person)){ map.get(manager).children.add(map.get(person)); } else{ map.get(manager).children.add(personNode); map.put(person, personNode); } } else{ map.put(manager, managerNode); if(map.containsKey(person)){ managerNode.children.add(map.get(person)); } else{ managerNode.children.add(personNode); map.put(person, personNode); } } } //find root Node root = null; for(int i = 0 ; i < input.length - 2 ; i++){ String manager = input[i].split("->")[0]; if(!childrenSet.contains(manager)){ root = map.get(manager); break; } } return root; } }
Build Relationship Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。