题目链接
    image.pngimage.png
    思路:找到所有的叶子节点,然后从叶子节点开始向上遍历,计算深度。
    递归思路:将当前的节点分别找到两边的深度大小,然后进行比较,找到最小值之后,将最小值+1返回。

    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. // return getMinDepth(root);
    19. return minDepth1(root);
    20. }
    21. // 1.我的代码
    22. public int getMinDepth(TreeNode node) {
    23. if(node == null) return 0;
    24. int left = getMinDepth(node.left);
    25. int right = getMinDepth(node.right);
    26. if(node.left == null && node.right != null) {
    27. return 1 + right;
    28. }
    29. if(node.left != null && node.right == null) {
    30. return 1 + left;
    31. }
    32. return 1 + (left > right ? right : left);
    33. }
    34. // 2.老师的代码
    35. public int minDepth1(TreeNode root) {
    36. if(root == null) return 0;
    37. if(root.left == null && root.right == null) return 1; // 当前只有一个节点
    38. int min = Integer.MAX_VALUE;
    39. if(root.left != null) {
    40. min = Math.min(minDepth(root.left), min);
    41. }
    42. // 这里不能使用else进行连接起来,否则的话会发生右边是空的话,就会一直获取的值为0
    43. if(root.right != null) {
    44. min = Math.min(minDepth(root.right), min);
    45. }
    46. return min+1;
    47. }
    48. }