Solution 1

  • TimeO(n)
  • SpaceO(n)

where, n is the number of nodes
Solved in 8 mins, all by yourself! Good job!

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    '''
    Time Complexity: O(n)
    Space Complexity: O(n)
    where, n is the number of nodes
    Solved in 8 mins, all by yourself! Good job!
    '''
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        out = 0
        def getMaxDepth(node):
            nonlocal out
            if not node:
                return 0
            left = getMaxDepth(node.left)
            right = getMaxDepth(node.right)
            out = max(out, left + right)
            return 1 + max(left, right)
        getMaxDepth(root)
        return out
Leet Code/python.py · L1540–1565