[leetcode]Minimum Depth of Binary Tree

树的递归。要注意对左右子树中有null的处理。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (root == null) return 0;
        boolean left = root.left != null;
        boolean right = root.right != null;
        
        if(left && right) {
            int minLeft = minDepth(root.left) + 1;
            int minRight = minDepth(root.right) + 1;
            if (minLeft > minRight) return minRight;
            else return minLeft;
        }
        else if (left) {
            return minDepth(root.left) + 1;
        }
        else if (right) {
            return minDepth(root.right) + 1;
        }
        else {
            return 1;
        }
        
    }
}

  

原文地址:https://www.cnblogs.com/lautsie/p/3247089.html