1. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

The take away here is that if any node is empty, there is no path, so cannot count as a minium depth.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int l = minDepth(root.left);
        int r = minDepth(root.right);
        if( l !=0 && r != 0){
            return Math.min(l,r) + 1;
        }else if(l == 0){
            return r +1;
        }else{
            return l+1;
        }


    }
}

results matching ""

    No results matching ""