Skip to content

Instantly share code, notes, and snippets.

@riyafa
Created September 16, 2022 07:52
Show Gist options
  • Save riyafa/7895c08c28125ddfe80db1369d4ec350 to your computer and use it in GitHub Desktop.
Save riyafa/7895c08c28125ddfe80db1369d4ec350 to your computer and use it in GitHub Desktop.
class MinimumDepthBinaryTreeBFS {
public int minDepth(TreeNode root) {
if(root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 0;
while(!queue.isEmpty()) {
level++;
int size = queue.size();
for(int i = 0; i < size; i++) {
TreeNode node = queue.remove();
if(node.left == null && node.right == null) {
//leaf node
return level;
}
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
return level;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment