111 二叉树的最小深度

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public int minDepth(TreeNode root) {
  18. if (root == null)
  19. return 0;
  20. else if (root.left == null && root.right == null)
  21. return 1;
  22. else if (root.left == null && root.right != null)
  23. return 1 + minDepth(root.right);
  24. else if (root.left != null && root.right == null)
  25. return 1 + minDepth(root.left);
  26. else
  27. return 1 + Math.min(minDepth(root.left), minDepth(root.right));
  28. }
  29. }