Java Code with explanation

  • 0

    In case you are wondering some +1s in other solutions, here is the explanation. The problem requires us to find the min depth to a leaf node. A check like root==null goes to a non-leaf mode so it is not enough to verify that. So what we need is to verify a real leaf node and then keep a count of that. Essentially, when you find a leaf node (i.e. whose right and left children are null, you set a count of 1). Now, we merely need to find minimum among two values.

    public int minDepth(TreeNode root) {
            if(root==null) {
                return 0;
            if(root.left ==null && root.right==null) {
                //leaf node.
                return 1;
            return Math.min(root.left!=null?1+minDepth(root.left):Integer.MAX_VALUE,

Log in to reply

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