leetcode-Given a binary tree, find its minimum depth

第一题

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.

返回一个二叉树的最短深度,即从根节点到叶子节点的所有路径中中,包含最少节点的那条路径上的节点个数

public class Solution {
    public int run(TreeNode root) {
        if(root == null)
            return 0;
        int i = run(root.left);
        int j = run(root.right);
        return (i == 0 || j == 0) ? i+j+1 : Math.min(i, j)+1;
    }
}

  这段代码是网上大神的,使用了递归的思想。

  当遇到空节点(即叶子节点的子节点)时,返回0,表示叶子节点的子树的最短深度为0(叶子节点没有子树)。对于非叶子节点,利用run函数得到其左右子树的最短深度,将其中比较短的那条子树的最短深度+1(要加上本节点)后返回,特别的,如果其左右子树中的有一条为空,则返回非空子树的最短深度+1,只是因为当存在空子树时,过此点的最小深度路径之经过非空的那条子树。当然,如果左右子树都为空,说明当前节点为叶子节,返回值为1。

转载于:https://www.cnblogs.com/qj4d/p/7078456.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值