求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
    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.

    分析:不管对什么二叉树,一个左分支,一个右分支,结果返回子分支的最小深度加1,所以用递归
    注意细节:如果有一个分支不为空,则返回另一个分支;如果节点数为null,返回0

    1. public class TreeNode {
    2. int val = 0;
    3. TreeNode left = null;
    4. TreeNode right = null;
    5. }

    代码:

    1. public class Solution {
    2. /**
    3. *
    4. * @param root TreeNode类
    5. * @return int整型
    6. */
    7. public int run (TreeNode root) {
    8. if(root == null) {
    9. return 0;
    10. }
    11. int left = run(root.left);
    12. int right = run(root.right);
    13. if(left==0) {
    14. return right+1;
    15. }
    16. if(right==0) {
    17. return left+1;
    18. }
    19. return (left<=right?left:right)+1;
    20. }
    21. }

    对于求最小深度,bfs的方法虽然空间复杂度会更高,但是理论上效率会更快。
    bfs代码如下:

    1. public int minDepth(TreeNode root) {
    2. if (root == null) {
    3. return 0;
    4. }
    5. Queue<TreeNode> queue = new LinkedList<>();
    6. queue.add(root);
    7. int deep = 0;
    8. while (!queue.isEmpty()) {
    9. int size = queue.size();
    10. deep++;
    11. for (int i = 0; i < size; i++) {
    12. TreeNode node = queue.poll();
    13. if (node.left == null && node.right == null) {
    14. return deep;
    15. }
    16. if (node.left != null) {
    17. queue.offer(node.left);
    18. }
    19. if (node.right != null) {
    20. queue.offer(node.right);
    21. }
    22. }
    23. }
    24. return deep;
    25. }