convert n-tree to dictionary based on depth

public Map<Integer, List<Integer>> toDict() {

Map<Integer, List<Integer>> dict = new HashMap<>();
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int depth = 0;

while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();

for (int i = 0; i < levelSize; i++) {
Node node = queue.poll();
currentLevel.add(node.getValue());

// Add all children of the current node to the queue
for (Node child : node.children) {
queue.add(child);
}
}
dict.put(depth, currentLevel);
depth++;
}
return dict;
}
public Map<Integer, List<Integer>> toDict() {

Map<Integer, List<Integer>> dict = new HashMap<>();
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int depth = 0;

while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();

for (int i = 0; i < levelSize; i++) {
Node node = queue.poll();
currentLevel.add(node.getValue());

// Add all children of the current node to the queue
for (Node child : node.children) {
queue.add(child);
}
}
dict.put(depth, currentLevel);
depth++;
}
return dict;
}
I wrote this function to convert a tree into a dictionary where the depth is mapped to the nodes on that depth (i.e. 0->root) is there a better way to do this?
3 Replies
JavaBot
JavaBot2mo ago
This post has been reserved for your question.
Hey @asdru! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
szatkus
szatkus2mo ago
You can replace the loop with queue.addAll(node.children)
JavaBot
JavaBot2mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server