# Help. what's wrong with this code.

• /**

• Definition for a binary tree node.

• public class TreeNode {

• ``````int val;
``````
• ``````TreeNode left;
``````
• ``````TreeNode right;
``````
• ``````TreeNode(int x) { val = x; }
``````
• }
*/
public class Solution {

Queue<TreeNode> holder = new LinkedList<TreeNode>();
int count = 1;

public int minDepth(TreeNode root) {

`````` if(root == null)
return 0;

return helper(root);
``````

}

public int helper(TreeNode node){

``````    holder.offer(node);
int size = holder.size();

while(!holder.isEmpty()){

for(int i = 0; i < size; ++i){

TreeNode tmp = holder.poll();

if(tmp.left == null && tmp.right == null)
return count;

if(tmp.left != null)
holder.offer(tmp.left);

if(tmp.right != null)
holder.offer(tmp.right);

}
count++;

}

return count;

}
``````

}

• First of all, your code is wrong because you put the line `int size = holder.size()` outside of the while loop.
Here is the modified code:

``````public class Solution {
Queue<TreeNode> holder = new LinkedList<TreeNode>();
int count = 1;
public int minDepth(TreeNode root) {
if(root == null)
return 0;
return helper(root);
}

public int helper(TreeNode node){
holder.offer(node);

while(!holder.isEmpty()){
int size = holder.size();
for(int i = 0; i < size; ++i){

TreeNode tmp = holder.poll();

if(tmp.left == null && tmp.right == null)
return count;

if(tmp.left != null)
holder.offer(tmp.left);

if(tmp.right != null)
holder.offer(tmp.right);
}
count++;
}
return count;
}
}
``````

Secondly, I'm not sure why you got 1 down vote. However, since you are new to leetcode, just let you know that you can format your question to look better. For example, you can select the code, press "Ctrl + K" and see the Preview, etc.

Enjoy leetcode ^_^.

• thank you!!!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.