Leetcode: Minimum Depth of Binary Tree

来源:互联网 发布:大数据培训课程有哪些 编辑:程序博客网 时间:2024/06/05 15:16

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

# Definition for a binary tree node.# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass 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))
0 0