educative.io

Educative

Why doesn't this problem include a recursion based solution?

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

Hello @Peter_Litvak,

Thank you for suggesting this recursive solution to this problem. Unfortunately, most problems don’t have recursive solutions, but we are working on them, and soon you will get the recursive solutions. You can explore other courses where we explicitly covered the recursion and recursion-related problems. e.g., Recursion for Coding Interviews in Java

I hope this will help you, but please let me know if you still have any questions.

Thank You :blush: