104. Maximum Depth of Binary Tree [easy] (Python)

3592 ワード

タイトルリンク
https://leetcode.com/problems/maximum-depth-of-binary-tree/
タイトル
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
タイトル翻訳
ツリーの最大深さを求めるツリーを指定します.最大深度(Max Depth)とは、ルートノードから最も遠いリーフノードまでの最長パスのノード数です.
考え方
考え方1
深度優先探索(DFS)、再帰的に解く.
コード#コード#
# 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 maxDepth(self, root):
        """ :type root: TreeNode :rtype: int """
        if root == None:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

考え方2
広さ優先探索(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 maxDepth(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 q[0].left:
                    q.append(q[0].left)
                if q[0].right:
                    q.append(q[0].right)
                del q[0]
        return depth

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