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

给定一个二叉树,求其最大深度。 
最大深度指的是,从根节点到最远的叶子节点的最长路径的节点个数。

思路方法

思路一

深度优先搜索(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 max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

思路二

广度优先搜索(BFS),利用队列求解

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        depth = 0
        q = [root]
        while q:
            depth += 1
            for i in range(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

 

点赞