private void convertTreeToList(JSONArray tree, JSONArray flattened) throws JSONException {
        int nLeaves = tree.getInt(0);
        List<JSONObject> leaves = new ArrayList<JSONObject>();
        if (nLeaves > clusterNumLeavesThreshold) {
            if (tree.get(2) instanceof JSONArray) {
                convertTreeToList((JSONArray) ((JSONArray) tree).get(2), flattened);
            } else {
                JSONArray cluster = new JSONArray();
                cluster.put(tree.get(2));
                flattened.put(cluster);
            }
            if (tree.get(3) instanceof JSONArray) {
                convertTreeToList((JSONArray) ((JSONArray) tree).get(3), flattened);
            }  else {
                JSONArray cluster = new JSONArray();
                cluster.put(tree.get(3));
                flattened.put(cluster);
            }
        } else {
            ArrayList<JSONObject> clusterleaves = new ArrayList<JSONObject>();
            if (tree.get(2) instanceof JSONArray) {
                getAllLeaves((JSONArray)((JSONArray) tree).get(2), clusterleaves);
            } else leaves.add((JSONObject)tree.get(2));
            if (tree.get(3) instanceof JSONArray) {
                getAllLeaves((JSONArray)((JSONArray) tree).get(3), clusterleaves);
            } else leaves.add((JSONObject)tree.get(3));
            JSONArray group = new JSONArray();
            for (JSONObject jso : clusterleaves) group.put(jso);
            if (clusterleaves.size() > 0) flattened.put(group);
        }
    }