0% completed
Problem Challenge 2: Minimum Height Trees (hard)
.....
.....
.....
Anonymous
· 2 years ago
from collections import deque class Solution: # build a unidrictional graph def build_graph(self, nodes, edges): graph, indegree = {}, {} for i in range(nodes): graph[i] = [] indegree[i] = 0 for node1, node2 in edges: graph[node1].append(node2) graph[node2].append(node1) indegree[node1] += 1 indegree[node2] += 1 return(graph, indegree) def findTrees(self, nodes, edges): if nodes == 1: return [0] graph, indegree = self.build_graph(nodes, edges) q = deque([x for x in indegree if indegree[x] == 1]) result = [] # topological ordering can be done on unidirectional graph too # for that we should do indegree[neighbor] == 1 as edge nodes are linked # topological finds the center
Anonymous
· 4 years ago
Can you add images to explain main solution with the 'P' root tree and 'M' subtree description? Thanks
Anonymous
· 4 years ago
Python3 solution fails on test case { nodes = 3, edges = [[0,1],[0,2]] } on LeetCode for LC 310. Minimum Height Trees ( https://leetcode.com/problems/minimum-height-trees/ ).
Anonymous
· 4 years ago
Could you explain more in-depth why the list of MHTs will only have one or two nodes?
Anonymous
· 4 years ago
This question needs a good few diagrams to explain the 'centroid' graph finding idea, as it's not that intuitive from the description unfortunately. It may also benefit to explain the logical progression from a O(N^2) BFS or DFS brute-force idea to the optimal topological sort idea (with diagrams).
An alternate in-depth explanation of this solution exists on Leetcode here: (Q. 310: https://leetcode.com/problems/minimum-height-trees/solution/ ).
Reading Progress
0%