Instinct understand in Python

  • 0

    Recursion with the return [depth of subtree, max_diameter of subtree].

    def diameterOfBinaryTree(self, root):
        return self.helper(root)[1]
    def helper(self, root):
        if not root:
            return [0,0]
        #[e0,e1]: e0, subtree height; e1, max_diameter of subtree
        left = self.helper(root.left)
        right = self.helper(root.right)
        return [max(left[0], right[0]) + 1, max(left[1], right[1], left[0]+right[0])]

Log in to reply

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