二叉树的算法实战 Minimum Depth of a Binary Tree

题目

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.
复制代码

主要代码

- (int)minimumDepth:(DSTreeNode *)root
{
    //1
    if (root == nil) {
        return 0;
    }
    //2
    if (root.leftChild == nil) {
        return [self minimumDepth:root.rightChild]+1;

    }
    //3
    if (root.rightChild == nil) {
        return [self minimumDepth:root.leftChild]+1;

    }
    //4
    return MIN([self minimumDepth:root.leftChild], [self minimumDepth:root.rightChild])+1;

}
复制代码

思路

  1. 遍历二叉树的每个节点,如果当前节点是叶子节点,则返回1。

  2. 如果不是叶子节点,且左子树为null,然后递归右子树。

  3. 如果不是叶子节点且右子树为null,然后递归左子树。

  4. 如果不是叶子节点,且左右子树不为null那么取递归后两者最小值。

小结

  • 由于遍历树的每个节点,因此时间复杂度是O(n)。

  • 当然还有其他不错的思路比如用层级遍历的方法,返回第一个遇到叶子节点的深度。

GitHubDemo资源

github.com/renmoqiqi/1…

转载于:https://juejin.im/post/5cfdb625f265da1baf7cdfcd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值