private void collapse(JSONArray tree, JSONArray flattened) throws JSONException {
        double dist = tree.getDouble(1);
        int nLeaves = tree.getInt(0);
        List<JSONObject> leaves = new ArrayList<JSONObject>();
        if (dist == -1 || (nLeaves > clusterNumLeavesThreshold || dist > clusterDistThreshold)) {
            if (tree.get(2) instanceof JSONArray) {
                collapse((JSONArray) ((JSONArray) tree).get(2), flattened);
            } else {
                flattened.put((JSONObject)tree.get(2));
            }
            if (tree.get(3) instanceof JSONArray) {
                collapse((JSONArray) ((JSONArray) tree).get(3), flattened);
            } else {
                flattened.put((JSONObject)tree.get(3));
            }
        } else {
            if (tree.get(2) instanceof JSONArray) {
                getAllLeaves((JSONArray)((JSONArray) tree).get(2), leaves);
            } else leaves.add((JSONObject)tree.get(2));
            if (tree.get(3) instanceof JSONArray) {
                getAllLeaves((JSONArray)((JSONArray) tree).get(3), leaves);
            } else leaves.add((JSONObject)tree.get(3));
            JSONObject dupes = new JSONObject();
            dupes.put("dupes", leaves);
            tree.put(3, dupes);
            JSONObject best = leaves.get(0);
            tree.put(2, best);
            JSONObject cluster = new JSONObject();
            leaves.remove(0);
            cluster.put("id", best.get("id"));
            cluster.put("dupes", leaves);
            flattened.put(cluster);
        }
    }