/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型
     */
    int ans = 0x3f3f3f;
    int minDepth(TreeNode* root) {
        // write code here
        if (!root)return 0;
        dfs(root, 0);
        return ans;
    }
    int dfs(TreeNode* root, int cnt) {
        if (root->left == nullptr && root->right == nullptr) {
            ans = min(ans, cnt + 1);
            return 0;
        }
        if (root->left)dfs(root->left, cnt + 1);
        if (root->right)dfs(root->right, cnt + 1);
        return 0;
    }
};

一、题目考察的知识点

二叉树遍历

二、题目解答方法的文字分析

如果当前节点的左子树为空,右子树为空,那么这个节点就是叶子结点,那么就可以更新记录一次,然后继续递归。

三、本题解析所用的编程语言

c++