Created
September 16, 2022 07:52
-
-
Save riyafa/7895c08c28125ddfe80db1369d4ec350 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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