题解 | #二叉树的最小深度#

二叉树的最小深度

http://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724

树的问题使用递归,注意叶子节点的定义是其左右子均为空,此时将其深度加入结果数组,最后取最小深度:

class Solution {
public:
    vector<int> res;
    int run(TreeNode* root) {
        if(root==nullptr)
            return 0;
        dfs(root, 1);
        return *min_element(res.begin(), res.end());
    }
    void dfs(TreeNode* root, int depth){
        if(root->left==nullptr && root->right==nullptr){
            res.emplace_back(depth);
            return ;
        } 
        if(root->left)
            dfs(root->left, depth+1);
        if(root->right)
            dfs(root->right, depth+1);
        return ;
    }
};
全部评论

相关推荐

豆泥🍀:同26届,加油,我也还没找到查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务