import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;


/**
 * Class represents trie
 */
class TrieNode
{
    boolean isLeaf = false;    // set when node is a leaf node
    Map<String, TrieNode> children = new HashMap<>();

    public void insert(String str) {
        if (str != null && !str.isEmpty()) {
            String[] strSeq = str.split("[\\s]+");

            // start from current node
            TrieNode curr = this;

            for (int i = 0; i < strSeq.length; i++)
            {
                // create a new node if path doesn't exists
                if (!curr.children.containsKey(strSeq[i])) {
                    curr.children.put(strSeq[i], new TrieNode());
                }
                // go to next node
                curr = curr.children.get(strSeq[i]);
            }

            curr.isLeaf = true;
        }
    }
    
    public HashSet<TrieNode> getChildrenTrieNodes() {
        HashSet<TrieNode> res = new  HashSet<>();
        for (String c: children.keySet()) {
            res.add(children.get(c));
        }
        return res;
    }

    public void printTrie() {
        printTrieWithParams(this,0);
    }

    private void printTrieWithParams(TrieNode node, int offset) {
        offset += 1;

        for (TrieNode tn:node.getChildrenTrieNodes()) {
            Iterator<Map.Entry<String, TrieNode>> it = node.children.entrySet().iterator();
            if (it.hasNext()) {

                Map.Entry<String, TrieNode> entry = it.next();

                for (int i = 0; i < offset; i++) {
                    System.out.print(" ");
                }

                System.out.println(entry.getKey());

                if(node.isLeaf) {
                    System.out.println();
                }

                node = entry.getValue();
                printTrieWithParams(node,offset);
            }
        }
    }
    
}

public class Main {
  public static void main(String[] args) {
	TrieNode trie = new TrieNode();
	List<String> inputs = new ArrayList<>();
	
	String input_0 = "abcd";
    String input_1 = "abcd abcd";
    String input_2 = "1 2 3 STRING HERE";

    inputs.add(input_0);
    inputs.add(input_1);
    inputs.add(input_2);
    
    
        for (String s : inputs) {
            trie.insert(s);
        }
        
    trie.printTrie();
  }
}