Python O(n)


  • 0
    A
    class Solution(object):
        def __init__(self):
            self.dia = 0
        def sub(self, root):
            if not root:
                return 0
            left = self.sub(root.left)
            right = self.sub(root.right)
            t = left+right
            self.dia = max(t, self.dia)
            return 1+max(left, right)
            
        def diameterOfBinaryTree(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.sub(root)
            return self.dia
    

Log in to reply
 

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