"原文链接 [链接] Description: 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 .."

[每日 LeetCode] 111. Minimum Depth of Binary Tree

原文链接 [每日 LeetCode] 111. Minimum Depth of Binary Tree

Description:

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.

Note: A leaf is a node with no children.

Example:

Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.


思路:本题要求二叉树的最小深度,注意和 [每日 LeetCode] 104. Maximum Depth of Binary Tree 的区别。本题依旧使用递归思想,需要注意的是在计算左子树和右子树深度的时候,判断是否等于 0,如果等于 0,说明该子树不存在,深度赋值为最大值。


C++ 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
         if(!root)
            return 0;
        if(!root->left && !root->right)
            return 1;
        int leftDepth = minDepth(root->left);
        int rightDepth = minDepth(root->right);
        if(leftDepth == 0)
            leftDepth = INT_MAX; 
        if(rightDepth == 0)
            rightDepth = INT_MAX;
        return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
    }
};

运行时间:8ms

运行内存:19.6M

  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    149 引用 • 35 回帖
  • Tree
    33 引用 • 5 回帖
  • Easy
    101 引用 • 10 回帖
回帖   
请输入回帖内容...