LeetCode Day17:二叉树的最小深度

发布于 2022-09-06  41 次阅读


题号:111
难度:Easy
链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree

思路

一开始跟二叉树最大深度一样做的,但报错了。

因为在根节点一个子结点为空,另一个不为空的情况下,其最小深度并不为1。

所以需要多加两句判定。

代码

#include <math.h>
using std::min;

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==nullptr) return 0;
        else if(root->left==nullptr&&root->right!=nullptr) return 1+minDepth(root->right);
        else if(root->left!=nullptr&&root->right==nullptr) return 1+minDepth(root->left);
        else return 1+min(minDepth(root->left),minDepth(root->right));
    }
};

提交结果

勉勉强强。

全文完