https://leetcode.com/problems/diameter-of-binary-tree/description/
I tried top down but I got a very large number, which means when I reached the bottom, either my return was not updating value all the way up or my impl is wrong
but this logic I solved in 백준 we just add the height of left subtree and height of right tree. But this actually is wrong?
Lets look at this case
If we just do root.left depth + root.right depth, we are gonna get 5 (2 -> 1 -> 3 -> 4 -> 6 -> 8). At first glance, this might seem correct, but there is actually a longer pathway with diameter 6 (9 -> 7 -> 5 -> 3 -> 4 -> 6 -> 8)! This is a problem for our 1st implementation since we assume the left side of the tree is involved with the diameter calculation.
i googled and found bottom-up
i didnt think of making a depth function and I think I just did diameterOfBinaryTree(root.left) + diameterOfBinaryTree(root,right)
btw why is this wrong for test case 2
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
return max(self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right)) + 1 if root else 0
but this is correct for test case 2?
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
def depth(node :Optional[TreeNode]) -> int:
return max(depth(node.left), depth(node.right))+1 if node else 0
return depth(root.left)+depth(root.right)