Help. what's wrong with this code.


  • -1
    S

    /**

    • 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;
    
    }
    

    }


  • 0
    D

    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 ^_^.


  • 0
    S

    thank you!!!


Log in to reply
 

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