Given a binary tree, find its minimum depth.

    The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

    Note: A leaf is a node with no children.

    Example:

    Given binary tree [3,9,20,null,null,15,7],

    1. 3
    2. / \
    3. 9 20
    4. / \
    5. 15 7

    return its minimum depth = 2.


    题意

    找到给定树从根到叶结点(两子树都为空的结点)的最短距离。

    思路

    递归或迭代。


    代码实现 - 递归

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

    代码实现 - 迭代

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. public int minDepth(TreeNode root) {
    12. if (root == null) {
    13. return 0;
    14. }
    15. Queue<TreeNode> q = new ArrayDeque<>();
    16. int depth = 0;
    17. q.offer(root);
    18. while (!q.isEmpty()) {
    19. depth++;
    20. int size = q.size();
    21. for (int i = 0; i < size; i++) {
    22. TreeNode cur = q.poll();
    23. // 第一次找到叶结点,说明已经为最短距离
    24. if (cur.left == null && cur.right == null) {
    25. return depth;
    26. }
    27. if (cur.left != null) {
    28. q.offer(cur.left);
    29. }
    30. if (cur.right != null) {
    31. q.offer(cur.right);
    32. }
    33. }
    34. }
    35. return depth;
    36. }
    37. }