- 543 二叉树的直径
- 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree - 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
解题思路:【python3】深度优先搜索:和求二叉树高度不一样的是,直径可能不穿过根节点,不能用根的左子树+右子树高度(可惜题目提醒了我,我也卡在这里好久= =)。递归遍历所有节点,计算其左子树与右子树的高度(l_depth,r_depth),将最大值记录下来(self.length),返回该值即可。
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root: return 0
self.length = 0
def branchDepth(cur):
if not cur: return 0
l_depth = branchDepth(cur.left)
r_depth = branchDepth(cur.right)
self.length = max(self.length, l_depth+r_depth)
return max(l_depth, r_depth)+1
branchDepth(root)
return self.length