Tree BFS Technique and Question Bank

Overview

  • Level Order Traversal using BFS is an important technique used in a lot of problems.
  • This post won't go into the science of BFS or trees, but aims to provide a template needed to solve problems of this theme.
  • The same techinque can be extended to N-ary tree with little modification
  • This is meant to be a continuosly improving post and I'll keep updating it and add more problems as I progress.
  • Collaboration works wonders so I'd encourage anyone reading this post to feel free to contribute for the benefit of the community.

Algorithm:

  • Create a queue for BFS with root as the seed value
  • Do while the q is not empty
    • For size of q = n, iterate over the q n-times
      • Poll a node from the q and add it to the level.
      • If the node's left child is non-null, then add it to the q. Repeat for right child
    • Add the level to list of levels

Basic Code Template:

T/S: O(n)/O(w), where n = number of nodes in the tree and w = max nodes at any level

public List<List<Integer>> levelOrder(TreeNode root) {
	if (root == null)
		return List.of();

	var lot = new ArrayList<List<Integer>>();
	var q = new ArrayDeque<>(List.of(root));

	while (!q.isEmpty()) {
		var level = new ArrayList<Integer>();

		for (var i = q.size(); i > 0; i--) {
			var node = q.poll();
			level.add(node.val);

			if (node.left != null)
				q.add(node.left);
			if (node.right != null)
				q.add(node.right);
		}
		lot.add(level);
	}
	return lot;
}

Question Bank

Legend: P = Premium


Comments and contributions for improvement are appreciated. Thanks!

Comments (4)