Empty tree should return -1, not 0

  • 0

    I think empty tree's diameter should be -1. Because a single node tree's diameter is 0 (it has zero edge). To separate an empty tree from it, empty tree's diameter should be -1. The leetcode test sets it to 0 which is inappropriate. My code:

        def helper(root):
            # return (diameter, longest path from root)
            # base case:
            if not root:
                return -1, -1
            ld, lp = helper(root.left)
            rd, rp = helper(root.right)
            d = max(ld, rd, lp+1+rp+1)
            p = max(lp+1, rp+1)
            return d, p
        diameter, _ = helper(root)
        return diameter

Log in to reply

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