【LeetCode】111. Minimum Depth of Binary Tree解法及注释,Java,C++,DFS

111. Minimum Depth of Binary Tree

 Total Accepted: 104964 Total Submissions: 342426 Difficulty: Easy 

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.

【分析】
    给定一个二叉树,要求其最小深度,这和【LeetCode】104求最大深度的方法并没有本质的不同,在104题中我提供了一种DFS的方法,但就此题并不能直接套用,毕竟思想有差异:1.初始条件差异,我们将最小深度的初始值设为INT_MAX(Java中为Integer.MAX_VALUE);2.深度值更新条件差异,只有到达叶子结点才更新。此外,我在网上看到一个十分简洁的算法,采用的是递归的思想,这里我直接给出了。
【DFS版】
class Solution {
public:
    int minDepth(TreeNode* root) 
    {
       if(root==NULL)return 0;
       
       int minDepth=INT_MAX;
       DFS(root,0,minDepth);
       return minDepth;
    }
    
    void DFS(TreeNode* root,int depth,int &minDepth)
    {
        if(root==NULL)return;
        if(root->left==NULL&&root->right==NULL)
        {
            if(depth+1<minDepth)minDepth=depth+1;
        }
        else
        {
            DFS(root->left,depth+1,minDepth);
            DFS(root->right,depth+1,minDepth);
        }
    }
    
};


【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==NULL)return 0;
        int LDepth=minDepth(root->left);
        int RDepth=minDepth(root->right);
        
        if(LDepth==0&&RDepth==0)
        return 1;
        if(LDepth==0)
        LDepth=INT_MAX;
        if(RDepth==0)
        RDepth=INT_MAX;
        
        return min(LDepth,RDepth)+1;
    }
    
};



【Java版】

 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution 
{
    public int minDepth(TreeNode root) 
    {
        if(root==null)return 0;
        if(root.left==null&&root.right==null)return 1;
        
        int LDepth=minDepth(root.left);
        int RDepth=minDepth(root.right);
        
        if(LDepth==0)
        LDepth=Integer.MAX_VALUE;
        if(RDepth==0)
        RDepth=Integer.MAX_VALUE;
        return Math.min(LDepth,RDepth)+1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jin_Kwok

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值