Python | Leetcode Python题解之第543题二叉树的直径
题目:
题解:
class Solution:def diameterOfBinaryTree(self, root: TreeNode) -> int:self.ans = 1def depth(node):# 访问到空节点了,返回0if not node:return 0# 左儿子为根的子树的深度L = depth(node.left)# 右儿子为根的子树的深度R = depth(node.right)# 计算d_node即L+R+1 并更新ansself.ans = max(self.ans, L + R + 1)# 返回该节点为根的子树的深度return max(L, R) + 1depth(root)return self.ans - 1