Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
My simple solution

Mohammed Dh Abbas

May 29, 2024

from heapq import * class Solution: def dfs(self, node, max_heap): # if leaf node if node and not node.left and not node.right: return 1 left = right = 0 if node.left: left = self.dfs(node.left, max_heap) if node.right: right = self.dfs(node.right, max_heap) # heap is used to push the path lengths = left length + right length + node length = '1' heappush(max_heap, -(left + right + 1)) return max(left, right) + 1 def findDiameter(self, root): max_heap = [] self.dfs(root, max_heap) return -heappop(max_heap)

0

0

Comments
Comments
Mohammed Dh Abbas
Mohammed Dh Abbasa year ago

you don't really need a heap you could just store the max path in class variable and cross check that and update it each time. much better!

On this page

Problem Statement

Try it yourself