543. Diameter of Binary Tree

543. Diameter of Binary Tree

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def depth(self, root):
        if root==None:return 0
        l,r=self.depth(root.left),self.depth(root.right)
        self.ans=max(self.ans,l+r)
        return 1+max(l,r)
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        self.ans=0
        self.depth(root)
        return self.ans

计算每个branch的depth

你可能感兴趣的:(leetcode)