Thursday, May 28, 2015

L Question: 5668114807128064

public static Node buildTree(List<Relation> data){
  if(data==null) return new Node();
  Node root=new Node();
  HashMap<Integer,ArrayList<Relation>> tree = new HashMap<Integer,ArrayList<Relation>>();
  for(Relation d:data){
   if(d.parent==null)
    root=new Node(d.child,null,null);
   else{
    if(tree.containsKey(d.parent)){
     ArrayList<Relation> value=tree.get(d.parent);
     value.add(d);
    } else {
     ArrayList<Relation> value = new ArrayList<Relation>();
     value.add(d);
     tree.put(d.parent,value);
    }
   }
  }
  if(root==null) return root;
  Queue<Node> q = new LinkedList<Node>();
  q.add(root);
  while(!q.isEmpty()){
   Node x = q.poll();
   if(tree.containsKey(x.id)){
    ArrayList<Relation> value=tree.get(x.id);
    for(Relation v:value){
     Node child = new Node(v.child,null,null);
     q.add(child);
     if(v.isLeft) 
      x.left=child;
     else x.right=child;
    }
   }
  }
  return root;
 }

No comments:

Post a Comment