非递归解法可以套用广度优先算法解法,在循环中添加判断条件,如果节点左右子树均为NULL,则最小深度就在该层。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        queue<TreeNode *> queue;
        int level = 0;
        if(root) queue.push(root);
        
        while(!queue.empty())
        {
            level += 1;
            int n = queue.size();
            for(int i = 0;i < n;i++)
            {
                TreeNode * elem = queue.front();
                if(elem->left == NULL && elem->right == NULL)
                    return level;
                if(elem->left) queue.push(elem->left);
                if(elem->right) queue.push(elem->right);
                queue.pop();
            }
        }
        
        return level;
    }
};

运行结果:

Runtime: 324 ms, faster than 54.93% of C++ online submissions for Minimum Depth of Binary Tree.
Memory Usage: 144.4 MB, less than 5.02% of C++ online submissions for Minimum Depth of Binary Tree.

运行效率较低,仅击败54.93%
递归(DFS)的写法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == NULL) return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        
        return (left == 0 || right == 0) ? left + right + 1:min(left,right) + 1;
    }
};

运行结果:

Runtime: 344 ms, faster than 26.69% of C++ online submissions for Minimum Depth of Binary Tree.
Memory Usage: 146.5 MB, less than 5.02% of C++ online submissions for Minimum Depth of Binary Tree.

最后return语句判断left == 0,right ==0是为了处理根节点存在左子树或者右子树为空,如果存在一个子树为空,那么最小深度应该算另一个分支的最小深度。