Tree from nesting levels: Difference between revisions

m
Improved coding.
(New post.)
m (Improved coding.)
Line 1,216:
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
 
public final class TreeNestingLevels {
Line 1,237 ⟶ 1,236:
private static List<Object> createTree(List<Integer> list) {
return makeTree(list, 0, 1);
}
private static List<Object> makeTree(List<Integer> list, int index, int depth) {
List<Object> tree = new ArrayList<Object>();
int current;
Stack<List<Object>> stack = new Stack<List<Object>>();
stack.push(tree);
forwhile ( intindex item< :list.size() && depth <= ( current = list.get(index) ) ) {
whileif ( itemdepth !== stack.size()current ) {
tree.add(current);
if ( item > stack.size() ) {
index += 1;
List<Object> innerTree = new ArrayList<Object>();
} else {
stack.peek().add(innerTree);
tree.add(makeTree(list, index, depth + 1));
stack.push(innerTree);
final int position = list.subList(index, list.size()).indexOf(depth);
} else {
index += ( position == -1 ) ? list.size() : position;
stack.pop();
}
}
stack.peek().add(item);
}
return tree;
}
 
}
</syntaxhighlight>
894

edits