class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
# -- VERY good for a review!
# -- mine
res = [0]
def dfs(node):
if not node:
return 0
left = dfs(node.left)
right = dfs(node.right)
res[0] = max(left+right, res[0])
return 1 + max(left, right) # Don't forget +1 for current node!
dfs(root)
return res[0]
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter