Skip to content

Instantly share code, notes, and snippets.

@madhur
Created May 26, 2019 08:10
Show Gist options
  • Select an option

  • Save madhur/cafbc69955261a5d64779a1332b9a66a to your computer and use it in GitHub Desktop.

Select an option

Save madhur/cafbc69955261a5d64779a1332b9a66a to your computer and use it in GitHub Desktop.
Minmum depth of a tree
// java.util.* and java.util.streams.* have been imported for this problem.
// You don't need any other imports.
public int minTreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> currQ = new LinkedList<TreeNode>();
Queue<TreeNode> nextQ = new LinkedList<TreeNode>();
currQ.add(root);
int minlevel = 1;
while(!currQ.isEmpty()) {
TreeNode node = currQ.remove();
if(node.left== null && node.right == null) {
return minlevel;
}
if (currQ.isEmpty()) {
if(node.left!=null)
nextQ.add(node.left);
if (node.right !=null)
nextQ.add(node.right);
while(!nextQ.isEmpty()) {
currQ.add(nextQ.remove());
}
++minlevel;
}
}
return minlevel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment