Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

​

Solution: Problem Challenge 1: Tree Diameter

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 2 years ago

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)
Show 1 reply
A

Anonymous

· 4 years ago

Hello.

I'm having issues understanding how in the example 2, node 1 and node 2 are not counted in the diamater. I know it is supposed to be the longest path between two leaf nodes but in the code I don't see how it is reflected.

Thanks in advanced.

Show 3 replies
A

Anonymous

· 4 years ago

Would you mind comparing this problem and LeetCode's 543 ? https://leetcode.com/problems/diameter-of-binary-tree/

Show 3 replies
A

Anonymous

· 5 years ago

if leftTreeHeight is not None and rightTreeHeight is not None:

should be if leftTreeHeight == 0 and rightTreeHeight == 0:

Show 2 replies

Reading Progress

0%


Vote for new content