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],
    3 / \ 9 20 / \ 15 7return its minimum depth = 2.

    Runtime: 8 ms, faster than 97.02% of C++ online submissions for Minimum Depth of Binary Tree.

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

    树的遍历计数问题,需要注意的是出现左右节点不同时存在时,需要取存在子节点的那个分支计数。

    Runtime: 216 ms, faster than 99.76% of JavaScript online submissions for Minimum Depth of Binary Tree.
    Memory Usage: 76.9 MB, less than 21.04% of JavaScript online submissions for Minimum Depth of Binary Tree.

    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var minDepth = function(root) {
        if (!root) {
            return 0;
        }
        let depth = 1;
        const queue = [root];
        let size;
        while(queue.length > 0) {
            size = queue.length;
            for (let i = 0; i < size; i++) {
                node = queue.shift();
                if (!node.left && !node.right) {
                    return depth;
                }
                if (node.left) {
                    queue.push(node.left);
                }
                if (node.right) {
                    queue.push(node.right);
                }
            }
            depth++;
        }
        return depth;
    };