111.Minimum Depth of Binary Tree(Tree-Easy)

转载请注明作者和出处: http://blog.csdn.net/c406495762

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.

题目:判断二叉树的最小深度。也就是leaf tree,从叶子到根经过的结点的最小值。

思路:判断结点是否存在左子树和右子树。如果结点存在左子树或者右子数,说明没有到叶子,需要继续查询;如果结点不存在左子树和右子数,说明已经到达叶子。例如图1二叉树示意图,该二叉树的最小深度为3,也就是1->2->4、1->3->5。需要注意的是,如果根结点(root)为空,则最小深度为0。

图1 二叉树示例图

Language:cpp

递归方法:

/**
 * 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;
        int l = minDepth(root->left);
        int r = minDepth(root->right);
        return 1 + (l && r ? min(l, r) : max(l, r));
    }
};

Language:python

Python使用了两种方法,递归和迭代。通过运行对比发现,迭代的方法速度更快。

递归方法:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        d = map(self.minDepth, (root.left, root.right))
        return 1 + (min(d) or max(d))

迭代方法:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        queue = [root]
        height = 0
        while queue:
            # node = queue.pop(0)
            height += 1
            ls = []
            for temp in queue:
                if not temp.right and not temp.left:
                    return height
                if temp.left:
                    ls.append(temp.left)
                if temp.right:
                    ls.append(temp.right)
            queue = ls
        return height

代码获取:https://github.com/Jack-Cherish/LeetCode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jack-Cui

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

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

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

打赏作者

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

抵扣说明:

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

余额充值