111. Minimum Depth of Binary Tree [easy] (Python)

4478 ワード

タイトルリンク
https://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.
タイトル翻訳
最小深さを求めるツリーを指定します.最小深度(Min Depth)とは、ルートノードから最も近いリーフノードへの最も近いパスのノード数です.
考え方
考え方1
広さ優先探索(BFS)はキューで解く.
コード#コード#
# 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 == None:
            return 0

        depth = 0
        q = [root]
        while len(q) != 0:
            depth += 1
            for i in range(0, len(q)):
                if not q[0].left and not q[0].right:
                    return depth
                if q[0].left:
                    q.append(q[0].left)
                if q[0].right:
                    q.append(q[0].right)
                del q[0]

        return depth

考え方2
深さ優先探索(DFS)は,再帰的に解く.1つのノードの最小高さは、必ずしも2つのサブツリーの最小高さのうち小さいものではなく、1つのサブツリーが空の場合、ノードの最小高さは別のサブツリーの最小高さに等しいことに注意してください.
コード#コード#
# 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 == None:
            return 0

        if not root.left:
            return 1 + self.minDepth(root.right)
        elif not root.right:
            return 1 + self.minDepth(root.left)
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

説明この問題の対比として,類似問題:Maximum Depth of Binary Tree
PS:初心者はLeetCodeをブラシして、初心者はブログを書いて、書き間違えたり書いたりして、まだ指摘してください.ありがとうございます.転載は以下のことを明記してください.http://blog.csdn.net/coder_orz/article/details/51337522