解题思路

这题其实很简单,我们只需要知道如何遍历一棵二叉树即可完成。过程中有三件事情需要注意!首先,第一个节点(root节点)可能为空,所以可以直接判断然后返回0。之后,我们需要确保该节点的子节点全部为空才能判断这是一个叶子节点。所以我们有三个状态如下:

  1. 没有任何子节点,该子节点为叶子节点,返回长度(root子节点为 0
  2. 单边有子节点,该节点不是叶子节点,返回遍历单边的最短长度
  3. 左右都是子节点,找左边或者右边的最短长度

根据这三个状态,我们就能知道怎么去写代码了。

代码

/**
 * 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 findMinDepth(TreeNode* root, int now) {
        if(root == nullptr) return now;
        if(root->left == nullptr && root->right == nullptr) return now + 1;
        if(root->left == nullptr) return findMinDepth(root->right, now + 1);
        if(root->right == nullptr) return findMinDepth(root->left, now + 1);
        return min(findMinDepth(root->left, now + 1), findMinDepth(root->right, now + 1));
    }

    int minDepth(TreeNode* root) {
        int depth;
        if(root == nullptr) return 0;
        if(root->left == nullptr) {
            depth = findMinDepth(root->right, 1);
        } else if(root->right == nullptr)  {
            depth = findMinDepth(root->left, 1);
        } else {
            depth = min(findMinDepth(root->left, 1), findMinDepth(root->right, 1));
        }
        return depth;
    }
};