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. }
  21. Queue<TreeNode> q = new LinkedList<>();
  22. q.offer(root);
  23. int min = 0;
  24. while (!q.isEmpty()){
  25. int size = q.size();
  26. min++;
  27. for (int i = 0; i < size; i++) {
  28. TreeNode temp = q.poll();
  29. if (temp.left != null) q.offer(temp.left);
  30. if (temp.right != null) q.offer(temp.right);
  31. if (temp.left == null && temp.right == null){
  32. return min;
  33. }
  34. }
  35. }
  36. return min;
  37. }
  38. }
  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. //终止条件
  19. if (root == null) return 0;
  20. int left = minDepth(root.left);
  21. int right = minDepth(root.right);
  22. 这里要先判断左子树/右子树是否为null
  23. if (root.left == null && root.right != null) return right+1;
  24. if (root.left!= null && root.right == null) return left + 1;
  25. return 1+Math.min(left,right);
  26. }
  27. }

image.png