leetcode 543 Diameter of Binary Tree

python:

class Solution:
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.long = 0
        def findlong(root):
            if not root.left and not root.right:
                return 0
            x = findlong(root.left) + 1 if root.left else 0
            y = findlong(root.right) + 1 if root.right else 0
            
            self.long = max(self.long, x+y)
            return max(x,y)
        findlong(root)
        return self.long

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/81088838