对于普通二叉树的diameter。
543. Diameter of Binary Tree
543. https://leetcode.com/problems/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 diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:self.res = 0if not root:return self.resself.getdia(root)return self.resdef getdia(self, root):if not root:return 0left = self.getdia(root.left)right = self.getdia(root.right)self.res = max(self.res, left + right)return 1 + max(left, right)
换到这题,多了很多子树,那其实思路一样,只要维护全局最大值,并且选择最长的两个子树的路径长度加起来就好。用heap实现;注意判断heap里有没有东西。
"""
# Definition for a Node.
class Node:def __init__(self, val=None, children=None):self.val = valself.children = children if children is not None else []
"""class Solution:def diameter(self, root: 'Node') -> int:""":type root: 'Node':rtype: int"""if not root:return 0self.res = float('-inf')self.getdia(root)return self.resdef getdia(self, root):if not root:return 0heap = []for child in root.children:temp = self.getdia(child)heapq.heappush(heap, -temp)first = 0second = 0if heap:first = -1*heapq.heappop(heap)if heap: second = -1*heapq.heappop(heap)self.res = max(self.res, first + second)return 1 + first