码迷,mamicode.com
首页 > 其他好文 > 详细

Build Relationship Tree

时间:2016-10-26 07:27:32      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:put   contains   java   this   blog   []   person   ons   generated   

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

标签:put   contains   java   this   blog   []   person   ons   generated   

原文地址:http://www.cnblogs.com/joannacode/p/5998950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!