Day7 -104. Maximum Depth of Binary Tree

今日题目:104. Maximum Depth of Binary Tree

刚刚在群组看到在讨论
想说也来写一下哈哈哈哈

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:
https://ithelp.ithome.com.tw/upload/images/20210922/20140843MqPfvjWNXW.png

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:
Input: root = [1,null,2]
Output: 2

Example 3:
Input: root = []
Output: 0

Example 4:
Input: root = [0]
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

思路

使用BFS,以breadth为优先搜索

搜索过的root在进行判断後,自list中删除
如root尚有子点,则将其之子点append回list中

以此recursive後 即可获得depth

My solution

def maxDepth(root):
    
    depth = 0
    q = [root]
    
    if root is None: return 0
    
    while len(q)!=0:
        depth +=1
        for i in range(q[0]):
            if q[0].left:
                q.append(q[0].left)
            if q[0].right:
                q.append(q[0].right)
            del q[0]
    return depth

Result

https://ithelp.ithome.com.tw/upload/images/20210922/20140843tRuCUg0eWo.png

检讨

在讨论区看到的解答

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

是使用DFS
以深度为优先搜索


<<:  Youtube Data API 教学 - 频道资料我都要 search.list

>>:  [Day 7]想不到有梗的标题LA(前端篇)

亚马逊卖家第一场直播攻略

一、检查你的因特网连接情况。首先,你要检查你的因特网连接,确认它能够处理流媒体,而且你的生活不会有任...

Proxmox VE 启用客体机复写及搭配迁移功能使用

当客体机在 Proxmox VE 节点上运作且客体磁碟储存於节点的本机储存即区时,若想要让客体机的...

时间管理

你的时间不是你的时间 当年当上管理者几个月之後,突然感觉到一阵茫然。我会发现都过了一个季了,为什麽...

亚马逊卖家店铺销量低是为什么

不管是刚刚推出一个新的电商网站,还是在已有的平台上销售产品和服务,卖家们总是有很多困难要克服,比如销...

Lazada卖家如何应对恶意退货问题

跨境电商新手卖家入驻Lazada平台的也越来越多,由于对Lazada平台不是很熟悉,就会经常遇到各种...