Tree from nesting levels: Difference between revisions
Content deleted Content added
New post. |
m Improved coding. |
||
Line 1,216: | Line 1,216: | ||
import java.util.Arrays; |
import java.util.Arrays; |
||
import java.util.List; |
import java.util.List; |
||
import java.util.Stack; |
|||
public final class TreeNestingLevels { |
public final class TreeNestingLevels { |
||
Line 1,237: | Line 1,236: | ||
private static List<Object> createTree(List<Integer> list) { |
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>(); |
List<Object> tree = new ArrayList<Object>(); |
||
int current; |
|||
Stack<List<Object>> stack = new Stack<List<Object>>(); |
|||
stack.push(tree); |
|||
while ( index < list.size() && depth <= ( current = list.get(index) ) ) { |
|||
if ( depth == current ) { |
|||
tree.add(current); |
|||
if ( item > stack.size() ) { |
|||
index += 1; |
|||
List<Object> innerTree = new ArrayList<Object>(); |
|||
⚫ | |||
stack.peek().add(innerTree); |
|||
tree.add(makeTree(list, index, depth + 1)); |
|||
stack.push(innerTree); |
|||
final int position = list.subList(index, list.size()).indexOf(depth); |
|||
⚫ | |||
index += ( position == -1 ) ? list.size() : position; |
|||
stack.pop(); |
|||
} |
|||
} |
|||
stack.peek().add(item); |
|||
} |
|||
return tree; |
return tree; |
||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
</syntaxhighlight> |