Skip to content

Instantly share code, notes, and snippets.

@munguial
Last active April 11, 2020 17:20
Show Gist options
  • Save munguial/6af19d30d1daeed77064a82fddf35895 to your computer and use it in GitHub Desktop.
Save munguial/6af19d30d1daeed77064a82fddf35895 to your computer and use it in GitHub Desktop.
Day 11 - Diameter of binary tree
# https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3293/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Result:
def __init__(self, diameter, longestPath):
self.diameter = diameter
self.longestPath = longestPath
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
return self.computeDiameter(root).diameter
def computeDiameter(self, root: TreeNode) -> Result:
if not root:
return Result(0, 0)
L = self.computeDiameter(root.left)
R = self.computeDiameter(root.right)
diameter = max(L.longestPath + R.longestPath, L.diameter, R.diameter)
longestPath = max(L.longestPath, R.longestPath) + 1
return Result(diameter, longestPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment