提交 4deae999 编写于 作者: L laozhang

add python leetcode 543

上级 468798a1
......@@ -36,6 +36,7 @@
22. [左右叶子之和](./solution/tree/leetcode_404_.py)
23. [路径总和 III](./solution/tree/leetcode_437_.py)
24. [二叉树的堂兄弟节点](./solution/tree/leetcode_993_.py)
25. [二叉树的直径](./solution/tree/leetcode_543_.py)
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding=utf-8
"""
543. 二叉树的直径
"""
from solution import TreeNode
class Solution:
max = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root or (not root.left and not root.right):
return 0
def helper(root: TreeNode):
if not root:
return 0
a = helper(root.left) + 1
b = helper(root.right) + 1
#记录某个节点的最大直径
self.max = self.max if a + b - 2 < self.max else a + b - 2
res = a if a > b else b
return res
helper(root)
return self.max
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册