美文网首页
Minimum Depth of Binary Tree - 返

Minimum Depth of Binary Tree - 返

作者: 郑明明 | 来源:发表于2016-10-31 16:59 被阅读196次

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

  • 题目
    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;
    }

相关文章

网友评论

      本文标题:Minimum Depth of Binary Tree - 返

      本文链接:https://www.haomeiwen.com/subject/zeeputtx.html