【Leetcode】111. Minimum Depth of Binary Tree

题目地址:

https://leetcode.com/problems/minimum-depth-of-binary-tree/

求根节点到诸多叶子节点的距离中最短的那个。分治法。只需要注意,如果某棵子树的minDepth是 0 0 0,意味着这个子树是null,所以并不存在这课子树的树根到它的叶子节点的路径,当然就不存在最短距离,需要排除。代码如下:

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int left =  minDepth(root.left);
        int right =  minDepth(root.right);
        if (left == 0 || right == 0) {
            return left + right + 1;
        } else {
            return Math.min(left, right) + 1;
        }
	}
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。算法正确性可以由数学归纳法得到。

也可以这么写:

public class Solution {
    public int minDepth(TreeNode root) {
    	// 如果是空树,返回0
        if (root == null) {
            return 0;
        }
        // 初始化res为无穷大,然后尝试更新它
        int res = Integer.MAX_VALUE;
        // 如果左子树不为空,统计一下左子树高度
        if (root.left != null) {
            res = Math.min(res, minDepth(root.left));
        }
        // 如果右子树不为空,统计一下右子树高度
        if (root.right != null) {
            res = Math.min(res, minDepth(root.right));
        }
        // 如果res没被更新,说明左右子树都为空
        //(否则左右子树高度至少是1,res必会更新),此时返回1,否则返回res+1
        return res == Integer.MAX_VALUE ? 1 : res + 1;
    }
}

时空复杂度一样。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值