Minimum Depth of Binary Tree - 返回树的最小深度

这个算法可以和返回树的最大深度做一个对比,返回树的最大深度思路比较简单,

  • 题目
    Given a binary tree, find its minimum depth.
    The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
  • 分析
    我第一拿到这个算法的时候也不知道从何下手,但是仔细对比分析和最大深度的区别,可以发现他们的递归思路是一样的,在细节上的处理有不同。
  • 代码
    int minDepth(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        if (root->left == NULL && root->right == NULL) {
            return 1;
        }
        if (root->left == NULL) {
            return minDepth(root->right) + 1;
        }
        if (root->right == NULL) {
            return minDepth(root->left) + 1;
        }
        return min(minDepth(root->left), minDepth(root->right)) + 1;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容