AI工具人
提示词工程师

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

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

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

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

/**
 * 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);
    }
};
赞(0) 打赏
未经允许不得转载:XINDOO » Leetcode Minimum Depth of Binary Tree (面试题推荐)

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册