543.二叉树的直径

class Solution(object):
    def diameterOfBinaryTree(self, root):
        self.ans = 0
        def dfs(root):
            if not root:
                return 0
            l = dfs(root.left)
            r = dfs(root.right)
            self.ans = max(self.ans,l+r+1)
            return max(l,r)+1
        dfs(root)
        return self.ans-1

你可能感兴趣的:(543.二叉树的直径)