Just go through the tree.
class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def depth(p): if not p: return 0 left, right = depth(p.left), depth(p.right) self.ans = max(self.ans, left+right) return 1 + max(left, right) depth(root) return self.ans
@realisking It seems to me that
memo is useless, you're only calculating the height of each sub-tree once, it will always execute the
if p not in memo: block. Just try by yourself, add an
else to print something and you'll notice nothing get printed.
You are correct, thanks for pointing that out.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.