Simple Python

  • 10

    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)
            return self.ans

  • 0

    @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.

  • 0

    You are correct, thanks for pointing that out.

  • 0

    Nice. This Python is much better.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.