#543
Diameter of Binary Tree
easy· Treesruns: 0Given the root of a binary tree, return the length of the diameter of the tree. The diameter is the length (in edges) of the longest path between any two nodes in the tree. This path may or may not pass through the root.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 443
class Solution:
def diameterOfBinaryTree(self, root: TreeNode | None) -> int:
diameter = 0
def depth(node: TreeNode | None) -> int:
nonlocal diameter
if not node:
return 0
left = depth(node.left)
right = depth(node.right)
diameter = max(diameter, left + right)
return 1 + max(left, right)
depth(root)
return diameter
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.