543. Diameter of Binary Tree
https://leetcode.com/problems/diameter-of-binary-tree/
Python
DFS
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
ans = 0
def dfs(node):
if not node:
return 0
nonlocal ans
left_depth = dfs(node.left)
right_depth = dfs(node.right)
ans = max(ans, left_depth+right_depth)
return 1 + max(left_depth, right_depth)
dfs(root)
return ans