Satellite

in #italast month

import java.util.*;

public class Satellite {

private Node buildTree(int preId, List<Character> preorderInput, List<Character> inorderInput, int startId, int endId){
    if(startId > endId) return null;
    Node local = new Node(preorderInput.get(preId));
    if(startId == endId) return local;
    int index = startId;
    for(int i=startId; i<= endId;i++){
        if(local.value == inorderInput.get(i)) index = i;
    }
        
    local.left = buildTree(++preId,preorderInput, inorderInput, startId, index-1); 
    local.right = buildTree(++preId,preorderInput, inorderInput, index+1, endId); 
    return local;
    }

public Tree treeFromTraversals(List<Character> preorderInput, List<Character> inorderInput) {
    
    if(preorderInput.size() != inorderInput.size()) throw new IllegalArgumentException("traversals must have the same length");
    Set<Character> setVer = new HashSet<>(preorderInput);
    if(setVer.size() != preorderInput.size()) throw new IllegalArgumentException("traversals must contain unique items");
    // equals per verificare che due set abbiano gli stessi elmenti. 
    Set<Character> setVerIn = new HashSet<>(inorderInput);
    if(!setVer.equals(setVerIn)) throw new IllegalArgumentException("traversals must have the same elements");
    return new Tree(buildTree(0,preorderInput,inorderInput,0,preorderInput.size()-1));
}

}