Javascript ES6 Leaf Removal Solution


  • 0
    S
    var findMinHeightTrees = function(n, edges) {
      if (n == 1) return [0];
      
      let leaves = new Set();
      let edgeSet = new Map();
    
      edges.forEach((tuple) => {   
        edgeSet.set(tuple[0], typeof edgeSet.get(tuple[0]) === 'undefined' ? new Set([tuple[1]]) : edgeSet.get(tuple[0]).add(tuple[1]))
        edgeSet.set(tuple[1], typeof edgeSet.get(tuple[1]) === 'undefined' ? new Set([tuple[0]]) : edgeSet.get(tuple[1]).add(tuple[0]))
    
        leaves.add(tuple[0]);
        leaves.add(tuple[1]);
    
        if (edgeSet.get(tuple[0]).size > 1 ) leaves.delete(tuple[0]);
        if (edgeSet.get(tuple[1]).size > 1 ) leaves.delete(tuple[1]);
      })
    
      while(n > 2) {    
        n -= leaves.size;
        let newLeaves = new Set();
        
        leaves.forEach((val) => {
          let delVal = edgeSet.get(val).entries().next().value[0];
          edgeSet.get(delVal).delete(val);
          if (edgeSet.get(delVal).size === 1) newLeaves.add(delVal);
          leaves.delete(val);
        })
        
        leaves = newLeaves; 
      }
      
      return Array.from(leaves);
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.