您的位置:首页 > 其它

Leetcode: Minimum Depth of Binary Tree

2015-05-15 02:34 344 查看

Question

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.

Hide Tags Tree Depth-first Search

Analysis

This problem is slightly different from the problem “maximum depth of binary tree”. If left child of subroot is None, the minimum depth of this subroot is not 0 because we should keep searching the right node.

Solution

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

class Solution:
    # @param {TreeNode} root
    # @return {integer}
    def minDepth(self, root):
        return self.search(root)

    def search(self,subroot):
        if subroot==None:
            return 0

        if subroot.left==None:
            return self.search(subroot.right)+1

        if subroot.right==None:
            return self.search(subroot.left)+1

        return 1+min(self.search(subroot.left), self.search(subroot.right))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: