Just share a simple recursive solution

  • 2
    public class Solution {
        public int minDepth(TreeNode root) {
            if (root==null) return 0;   // height is zero
            int leftH = minDepth(root.left);  // get left height
            int rightH = minDepth(root.right);  // get right height
            if (leftH*rightH==0 && leftH!=rightH){  // only one of them is zero
                return (leftH!=0?leftH:rightH)+1;     // return non-zero one
            return Math.min(leftH,rightH)+1;  // else return the smaller one

    Nothing special... logic is presented in the comments.

  • 1
     if (leftH*rightH==0 && leftH!=rightH) 

    u can try XOR instead. like:

      if (leftH==0 ^ leftH==0) 

  • 0

    Great, didn't think about that. And the second one should be rightH?

Log in to reply

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