Minimum Depth of Binary Tree - LeetCode

702 ワード

Minimum Depth of Binary Tree - LeetCode
タイトル:
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. 分析:
木に関する問題はすべて再帰的に解決できるような気がします.最小パスを見つけてmin関数を使用します.
コード:
class Solution:
    # @param root, a tree node
    # @return an integer
    def minDepth(self, root):
        if not root:
            return 0
        if not root.right:
            return self.minDepth(root.left)+1
        elif not root.left:
            return self.minDepth(root.right)+1
        else:
            return min(self.minDepth(root.right),self.minDepth(root.left))+1