Something like this:
public static void levelOrderTraversal(BinaryTreeNode root) {
if(root == null) {
System.out.print(root);
return;
}
System.out.print(
bfs(Collections.singletonList(root), new StringBuilder())
);
}
private static StringBuilder bfs(List<BinaryTreeNode> nodes, StringBuilder sb) {
List<BinaryTreeNode> list = new ArrayList<>();
for(int i = 0; i < nodes.size(); i++) {
BinaryTreeNode node = nodes.get(i);
sb.append(node.data);
if(i + 1 < nodes.size()) {
sb.append(", ");
}
if(node.left != null) {
list.add(node.left);
}
if(node.right != null) {
list.add(node.right);
}
}
if(!list.isEmpty()) {
sb.append(" : ");
bfs(list, sb);
}
return sb;
}
And more generally why aren’t recursion based solutions given for many of the tree problems where applicable?
Type your question above this line.
Course: https://www.educative.io/collection/5642554087309312/5679846214598656
Lesson: https://www.educative.io/collection/page/5642554087309312/5679846214598656/170003