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

  • 0
    T

    @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

    @tanoabeleyra
    You are correct, thanks for pointing that out.


  • 0
    A

    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.