[leetcode]Minimum Depth of Binary Tree @ Python


原題地址:http://oj.leetcode.com/problems/minimum-depth-of-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.

解題思路:分幾種情況考慮:1,樹為空,則為0。 2,根節點如果只存在左子樹或者只存在右子樹,則返回值應為左子樹或者右子樹的(最小深度+1)。 3,如果根節點的左子樹和右子樹都存在,則返回值為(左右子樹的最小深度的較小值+1)。

代碼:

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

class Solution:
    # @param root, a tree node
    # @return an integer
    def minDepth(self, root):
        if root == None:
            return 0
        if root.left == None and root.right != None:
            return self.minDepth( root.right ) + 1
        if root.left != None and root.right == None:
            return self.minDepth( root.left ) + 1
        return min( self.minDepth( root.left ), self.minDepth( root.right ) ) + 1
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM