leetcode_111

题目来源:https://leetcode.com/problems/minimum-depth-of-binary-tree/

思路: ①如果根节点为空,则深度为0;
②如果左子树为空,则遍历右子树深度;
③如果右子树为空,则遍历左子树深度;
④否则,遍历左右子树深度,并返回最小值;

代码:
/**

  • Definition for a binary tree node.
  • public class TreeNode {
  • int val;
  • TreeNode left;
  • TreeNode right;
  • TreeNode(int x) { val = x; }
  • }
    */
    class Solution {
    public int minDepth(TreeNode root) {
    if(root == null){
        return 0;
    }
    if(root.left == null && root.right == null){
        return 1;
    }
    if(root.left == null){
    //注意要加上根节点的深度,即要+1
        return minDepth(root.right)+1;
    }
    if(root.right == null){
    //同上
        return minDepth(root.left)+1;
    }
    return Math.min(minDepth(root.left),minDepth(root.right))+1;//同+1
    

    }

}