首页 > 其他 > 详细

LeetCode Minimum Depth of Binary Tree

时间:2016-02-23 09:48:36      阅读:247      评论:0      收藏:0      [点我收藏+]

LeetCode解题之Minimum Depth of Binary Tree


原题

求一棵二叉树的最小高度,即从根节点到最近叶子节点的路径经过的节点数。

注意点:

例子:

输入:

    3
   /   9  20
    /     15   7
  /
 14

输出: 2

解题思路

可以通过树的广度优先遍历 Binary Tree Level Order Traversal 来实现,在广度优先遍历的过程中,每遍历一层就高度加一,如果某一个节点是叶子节点,那么当前的高度就是最小高度。

AC源码

# 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 root is None:
            return 0
        depth, curr_level = 0, [root]
        while curr_level:
            depth += 1
            next_level = []
            for n in curr_level:
                left, right = n.left, n.right
                if left is None and right is None:
                    return depth
                if left:
                    next_level.append(left)
                if right:
                    next_level.append(right)
            curr_level = next_level
        return depth


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

LeetCode Minimum Depth of Binary Tree

原文:http://blog.csdn.net/u013291394/article/details/50720623

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!