I have an array of strings that come from html tags ....
String[] Headers = {"H1", "H1", "H2", "H3", "H3", "H2", "H2", "H3", "H4", "H2", "H2", "H2", "H1", "H2", "H2", "H3", "H4", "H4", "H2" };
I need to turn into a tree structure. Where any Hn is a child of the last Hn-1
ROOT
H1
H1
...H2
......H3
......H3
...H2
...H2
......H3
.........H4
...H2
...H2
...H2
H1
...H2
...H2
......H3
.........H4
.........H4
...H2
This is similar to what needs to be done with recursion and something that when I see the solution, I'm going to kick myself for not thinking about it before. Has anyone got a solution for me?
Update
So, I tried several recursion options with absolute luck. As it turned out, I made this problem harder than it was.
Due to the test case that appeared,
String [] Headers = {"H1", "H1", "H3", "H3", "H5", "H4", "H4", "H4"};
bcorso, :
private void addChildren(TocItem root, Elements headers) {
if(headers == null || headers.size() == 0) return;
Map<Integer, TocItem> mostRecent = new HashMap<Integer, TocItem>(headers.size());
int startLevel = getTagLevel(headers.get(0)) - 1;
mostRecent.put(startLevel, root);
for(int i = 0; i < headers.size(); i++) {
Element htag = headers.get(i);
int level = getTagLevel(htag);
TocItem next = new TocItem(htag, level);
int offset = 1;
TocItem parent = mostRecent.get(level - offset);
while(parent == null && offset < level) {
offset++;
parent = mostRecent.get(level - offset);
}
if(parent != null) {
parent.addChild(next);
}
mostRecent.put(level, next);
}
}