前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode Minimum Depth of Binary Tree (面试题推荐)

Leetcode Minimum Depth of Binary Tree (面试题推荐)

作者头像
xindoo
发布2021-01-22 12:47:33
2640
发布2021-01-22 12:47:33
举报
文章被收录于专栏:XINDOO的专栏XINDOO的专栏

我其他leetcode结题代码见我github https://github.com/xindoo/leetcode

计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。

我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。

代码语言:javascript
复制
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int mindepth = 0;
    int minDepth(TreeNode *root) {
        if (NULL == root)
            return 0;
        else
            mindepth = 0x3f3f3f3f;
        dfs(root, 1);
        return mindepth;
    }
    void dfs(TreeNode *root, int depth) {
        if (NULL != root->left)
            dfs(root->left, depth+1);
        if (NULL != root->right)
            dfs(root->right, depth+1);
        if (NULL == root->left && NULL == root->right)
            mindepth = min(mindepth, depth);
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-10-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档