1530. Number of Good Leaf Nodes Pairs ## 思路 leaf之間的距離 = 兩個leaf到LCA的距離相加 ## Complexity d = distance Time: O(N d*2) Space: O(H) ## Code ```python # 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 countPairs(self, root: TreeNode, distance: int) -> int: def dfs(node): nonlocal ans if not node: return [] if not node.left and not node.right: return [1] left = dfs(node.left) right = dfs(node.right) for d1 in left: for d2 in right: if d1 + d2 <= distance: ans += 1 return [1+d for d in left + right if 1+d < distance] ans = 0 dfs(root) return ans ``` 補個參考提示寫的作法 build graph 再從每個leaf做BFS ```python # 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 countPairs(self, root: TreeNode, distance: int) -> int: graph = defaultdict(list) leaves = set() # build graph stack = [root] while stack: node = stack.pop() if node.left: graph[node].append(node.left) graph[node.left].append(node) stack.append(node.left) if node.right: graph[node].append(node.right) graph[node.right].append(node) stack.append(node.right) if not node.left and not node.right: leaves.add(node) # BFS ans = 0 for leaf in leaves: queue = deque([leaf]) seen = {leaf} dist = 0 while queue: for _ in range(len(queue)): node = queue.popleft() if node != leaf and node in leaves and dist <= distance: ans += 1 for neighbor in graph[node]: if neighbor not in seen: seen.add(neighbor) queue.append(neighbor) dist += 1 if dist > distance: break return ans // 2 ``` -- ※ 發信站: 批踢踢實業坊(ptt-website.tw), 來自: 185.213.82.26 (臺灣) ※ 文章網址: https://ptt-website.tw/Marginalman/M.1721273830.A.989
sustainer123: 剩我不熟LCA 07/18 11:38
dont: LCA週 連weekly premium (1740)也是LCA 07/18 11:43
DJYOMIYAHINA: 剩肥肥買p都沒刷p題了 07/18 11:52