Why my solution done wrong in [1,2,3,4,null,null,5],i tested it and return a different answer compared with submit


  • 0
    C
    public class Solution {
       static int  min_depth=Integer.MAX_VALUE;
    	static int rec=1;
    	public static int minDepth(TreeNode root) {
    		if (root==null) {
    			return 0;
    		}
    		if (isLeaf(root)) {
    			return 1;
    		}
    		setVal(root);
    		return min_depth;
    	}
    	public static void setVal(TreeNode root) {
    
    		if (isLeaf(root)) {	 
    			min_depth=min_depth<rec?min_depth:rec;
    			return;
    		}
    		 
    		if (root.left!=null) {   rec++;
    			setVal(root.left);
    			  rec--;
    		}
    		if (root.right!=null) { 
    		     rec++;
    			setVal(root.right);
    			  rec--;
    		}
    	  
    	}
    	public static boolean isLeaf(TreeNode node) {
    		if (node.right==null&&node.left==null) {
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    }

Log in to reply
 

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