Short Python recursive solution


  • 0

    helper method returns a pair of 2 values: the longest path in a subtree and its height.

    class Solution(object):
        def helper(self, root):
            if not root: return 0, -1
            pl, hl = self.helper(root.left)
            pr, hr = self.helper(root.right)
            return max(pl, pr, hl + hr + 2), max(hl, hr) + 1
            
        def diameterOfBinaryTree(self, root):
            return self.helper(root)[0]
    

Log in to reply
 

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