the best explanation in the whole universe, and don't know why those bad solution vedio got so many views, yours deserves more. PS: I think this problem should labelled as medium.
I think what trips us the most is ensuring we know the definition of height, depth, max height, max depth of a tree and/or node. In some sites, these are defined by number of edges but in others by number of nodes. Once you get these definitions right, the solution becomes even more clear. Thanks for the vid!
In regards to the variable scoping topic: Instead of creating a single field array, you can also use the `nonlocal` keyword as well. Though, it does add an extra line to your code, as it'll look something like this: nonlocal largest_diameter largest_diameter = max(largest_diameter, left_height + right_height)
Instead of using that list trick at the end, couldn't we just define "self.largest_diameter=0" then just use self.largest_diameter everywhere that we reference it? This worked for me : class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: self.max_diam = 0 def height(root): if not root: return 0 left_height = height(root.left) right_height = height(root.right) diam = left_height + right_height self.max_diam = max(diam,self.max_diam) return max(left_height,right_height)+1 height(root) return self.max_diam
I have a question. Instead of calculating the withing the height function, i calculated the diameter at the end by using diameter = height(root.left) + height(root.right). This worked for most test cases except one. Why do I have to calculate the diameter within the height function and not after?
I just started algorithms after doing oop, I feel like Im always one step from solving the problem but I never find that step, is ok that Im going to RU-vid to find the solution or am I ruining my progress. Thank you
@@chi94 by thinking logically 😅 I am not saying it's not ok to look for solution on RU-vid or elsewhere but we should give it some tries to solve problems to strengthen our logical thinking.
I believe its not required to pass the same parameter to the nested function that is already a part of the parent function, we can directly access it. Feel free to correct me if I'm on the wrong direction!