543 - Diameter of a Binary Tree
Written on October 21, 2015
Tweet
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
ret = [0]
self.helper(root, ret)
return ret[0]
def helper(self, root, ret):
if not root:
return 0
left = self.helper(root.left, ret)
right = self.helper(root.right, ret)
ret[0] = max(ret[0], left + right)
return max(left, right) + 1