iT邦幫忙

0

leetcode with python: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.

給定一個binary tree,算它的最大深度

剛看到還以為有點複雜,結果做起來程式碼有夠精簡XD

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right))+1

如果是None代表跑到樹外了(底層之外),回傳0(樹外不算一層)
若非None則回傳左右節點向下探索後較深的一側的深度+1(算上自己這層的深度)
值不斷+1回傳直到root,我們便得到了此樹的最大深度
最後執行時間39ms(faster than 96.86%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言