{0,0,0,0,#,#,0,#,#,#,0}, output in eclipse is 4, but in OJ is 5, May I think in wrong way


  • 2
    L
       static int max =0;
       static int depth =1;
       public int maxdepth(TreeNode node)
    {
    	
    	
    	
    	
    	if(node!=null)
    	{
    		
    		
    		System.out.println(node.val+" "+depth);
    		
    		if(depth>max) {max=depth;}
    		
    		if(node.left!=null)
    		{  
    			depth++;
    			
    			maxdepth(node.left);
    			depth--;
    		}
    			
    	    if(node.right!=null)
    	    {
    	    	depth++;
    	    	maxdepth(node.right);
    	    	depth--;
    	    	
    	    }
    	    
    	    
    		
    		
    		
    	}
    	
    	
    	return max;
        
    }

  • 0
    S

    Here is the problem, System.out.println(node.val+" "+depth); .

    Do not print anything to stdout, or will lead to misjudge.


  • 0
    L

    Thanks for your answer:), I pasted the code from my eclipse, so the print message was not commented , I have commented the line in OJ test environment, but it is still the same error:(


  • 5
    B

    Not so long ago,I got a same result like you!I think maybe you didn't init max at maxdepth()

    public class Solution {
    static int max = 0;
    
    public int maxDepth(TreeNode root) {
        max = 0;// init static max = 0 for every case
        if(root!=null){
            NowDepth(root,1); 
        }
        return max;
    }
    
    static void NowDepth(TreeNode root,int depth){
        if(depth > max)
            max = depth;
        if(root.left!=null){
            NowDepth(root.left,depth+1);
        }
        if(root.right!=null){
            NowDepth(root.right,depth+1);
        }
    }
    

    }


  • 0
    L

    Thanks:) , it is accepted after your suggestion !


  • 0
    J

    it worked with me too!
    but please can you explain what is the difference between initializing "max" inside and outside maxdepth(), why it didn't work when initialized outside?


Log in to reply
 

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